Java8

函数式接口

Predicate<T>        T->boolean
     IntPredicate LongPredicate DoublePredicate

Consumer<T>      T->void
   IntConsumer LongConsumer DoubleConsumer

Function<T,R>     T->R
   IntFunction<R>
   IntToDoubleFunction
   IntToLongFunction
   LongFunction<R>
   LongToDoubleFunction
   LongToIntFunction
   DoubleFunction<T>
   ToIntFunction<R>
   ToLongFunction<T>
   ToDoubleFunction<T>
 
Supplier<T>     ()->T
   BooleanSupplier
   IntSupplier
   LongSupplier
   DoubleSupplier

UnarryOperator<T>   T->T
   IntUnaryOperator
   LongUnaryOperator
   DoubleUnaryOperator

BinaryOperator<T>    (T,T)->T
   IntBinaryOperator
   LongBinaryOperator
   DoubleBinaryOperator

BiPredicate<L,R>    (L,R)->boolean

BiConsumer<T,U>     (L,R)->void
   ObjIntConsumer<T>
   ObjLongConsumer<T>
   ObjDoubleConsumer<T>

BiFunction<T,U,R>    (T,U)->R
   ToIntBiFunction<T,U>
   ToLongBiFunction<T,U>
   ToDoubleFunction<T,U>
   

复合lambda表达式

List<Apple> list = Arrays.asList(new Apple(2), new Apple(3), new Apple(1), new Apple(4), new Apple(5));
list.sort(Comparator.comparing(Apple::getWeight));

//排序,调用Apple getWeight方法进行排序

 

 比较器复合

List<Apple> list = Arrays.asList(new Apple(2,"China"), new Apple(2,"Azk"), new Apple(1,"Korea"), new Apple(4,"Japan"), new Apple(5,"China"));
list.sort(Comparator.comparing(Apple::getWeight).reversed().thenComparing(Apple::getCountry));

//排序,先用重量排序,然后在反转,然后在根据国家排序

 

谓词复合

    public static void main(String[] args) {
        List<Apple> list = Arrays.asList(new Apple(2, "China"), new Apple(2, "Azk"), new Apple(1, "Korea"), new Apple(4, "Japan"), new Apple(5, "China"));
        list.sort(Comparator.comparing(Apple::getWeight).reversed().thenComparing(Apple::getCountry));

        Predicate<Apple> applePredicate1=(Apple apple)->apple.getWeight()>2;
        Predicate<Apple> applePredicate2= ((Predicate<Apple>) apple -> apple.getWeight() > 2).and(apple -> apple.getCountry().equals("China"));
       //筛选  苹果的重量大于2,同时属于China
    testFuHe(list,applePredicate2);   
  }
public static List<Apple> testFuHe(List<Apple> apples, Predicate<Apple> predicate) { ArrayList<Apple> as = new ArrayList<>(); for (Apple apple : apples) { if (predicate.test(apple)) { as.add(apple); } } return as; }

 函数复合

        Function<Integer,Integer> fun1=(num)->num*10;
        Function<Integer,Integer> fun2=(num)->num+10;

        Function<Integer, Integer> fun3 = fun1.andThen(fun2);       //调完fun1 在调用fun2
        Function<Integer, Integer> fun4 = fun1.compose(fun2);       //调用fun2的结果 然后在调用fun1

        Integer res3 = fun3.apply(5);
        Integer res4 = fun4.apply(5);

 

 流处理

流只能遍历一次。遍历完之后这个流就已经被消费掉了

流的Api

filter        中间        Stream<T>    Predicate<T>        T->boolean
map       中间     Stream<R>  Function<T,R>      T->R
limit      中间     Stream<T>
sorted     中间     Stream<T>   Compartor<T>      (T,T)->int
distinct    中间     Stream<T>
flatMap     中间     Stream<T>  Function<T,Stream<R>>  T->Stream<R>



forEach     终端            Comsumer<T>       T->void      消费每个流的元素,返回一个void
count      终端     返回流中元素的个数。
collect     终端     把流归成一个集合,比如List,Map甚至Integer

reduce     终端     Optional<T>   BinaryOperator<T>   (T,T)->T

匹配
anyMatch    终端               Predicate<T>      T->boolean        看当中是否有一个匹配
allMatch    终端               Predicate<T>      T->boolean        看当中是否全部匹配
noMatch     终端               Predicate<T>      T->boolean        确保没有匹配

查找
findAny     终端     Optional<T>              返回当前流的任意元素
findFirst    终端     Optional<T>              查找第一个

数值
sum
min
max

 案例

public class Trader {
    private String name;
    private String city;
    public Trader(String name, String city) {
        this.name = name;
        this.city = city;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    @Override
    public String toString() {
        return "Trader{" +
                "name='" + name + '\'' +
                ", city='" + city + '\'' +
                '}';
    }
}
public class Transaction {
    private Trader trader;
    private int year;
    private int value;
    public Transaction(Trader trader, int year, int value) {
        this.trader = trader;
        this.year = year;
        this.value = value;
    }
    public Trader getTrader() {
        return trader;
    }
    public void setTrader(Trader trader) {
        this.trader = trader;
    }
    public int getYear() {
        return year;
    }
    public void setYear(int year) {
        this.year = year;
    }
    public int getValue() {
        return value;
    }
    public void setValue(int value) {
        this.value = value;
    }
}
 public static void main(String[] args) {
        Trader raoul = new Trader("Raoul", "Cambridge");
        Trader mario = new Trader("Mario", "Milan");
        Trader alan = new Trader("Alan", "Cambridge");
        Trader brian = new Trader("Brian", "Cambridge");
        List<Transaction> transactions = Arrays.asList(
                new Transaction(brian, 2011, 300),
                new Transaction(raoul, 2012, 1000),
                new Transaction(raoul, 2011, 400),
                new Transaction(mario, 2012, 710),
                new Transaction(mario, 2012, 700),
                new Transaction(alan, 2012, 950)
        );

        //找出2011年发生的所有交易,并按交易额排序(从低到高)。
        List<Transaction> res1 = transactions.stream().filter(transaction -> transaction.getYear() == 2011)
                .sorted(Comparator.comparing(Transaction::getValue)).collect(Collectors.toList());
        //交易员都在哪些不同的城市工作过?
        List<String> res2 = transactions.stream().map(transaction -> transaction.getTrader().getCity()).distinct().collect(Collectors.toList());
        //查找所有来自于剑桥的交易员,并按姓名排序。
        List<Transaction> res3 = transactions.stream().filter(transaction -> transaction.getTrader()
                .getCity().equals("Cambridge")).sorted(Comparator.comparing(o -> o.getTrader().getName())).collect(Collectors.toList());
        //返回所有交易员的姓名字符串,按字母顺序排序。
        List<String> res4 = transactions.stream().flatMap((Function<Transaction, Stream<String>>) transaction -> Stream.of(transaction.getTrader().getName()))
                .sorted().collect(Collectors.toList());
        //有没有交易员是在米兰工作的?
        Optional<Transaction> res5 = transactions.stream().filter(transaction -> transaction.getTrader().getCity().equals("Milan")).findAny();
        //打印生活在剑桥的交易员的所有交易额。
        transactions.stream().filter(transaction -> transaction.getTrader().getCity().equals("Cambridge"))
                .flatMap((Function<Transaction, Stream<?>>) transaction -> Stream.of(transaction.getValue())).forEach(System.out::println);
        //所有交易中,最高的交易额是多少?
        Optional<Transaction> res6 = transactions.stream().max(Comparator.comparingInt(Transaction::getValue));
        //找到交易额最小的交易。
        Optional<Transaction> res7 = transactions.stream().min(Comparator.comparingInt(Transaction::getValue));
    }

 

 构建流

由值创建流
Stream.of();
Stream<String> stringStream = Stream.of("one", "two", "three");


由数组创建流
Arrays.stream();
int[] nums={2,3,4,5,6};
IntStream stream = Arrays.stream(nums);


文件生成流
Stream<String> lines = Files.lines(Paths.get("xxx.txt"), Charset.defaultCharset());


无限生成流
Stream.iterate(1, integer -> integer+1).limit(10).forEach(System.out::println);    //每个新值都是依照上一次的值按规则生成的
Stream.generate(Math::random).limit(10).forEach(System.out::println);

收集器 

预定义收集器

transactions.stream().map(transaction -> transaction.getValue()).collect(Collectors.counting());  // Collectors.counting()统计个数

transactions.stream().collect(Collectors.maxBy(Comparator.comparingInt(Transaction::getValue)));   // Collectors.maxBy()  取最大值

transactions.stream().collect(Collectors.summingInt(Transaction::getValue));        //求和

transactions.stream().collect(Collectors.averagingInt(Transaction::getValue));        //求平均

transactions.stream().map(transaction -> transaction.getTrader().getName()).collect(Collectors.joining(","));    //字符串拼接

 分组

 transactions.stream().collect(Collectors.groupingBy(new Function<Transaction, Integer>() {
     @Override
     public Integer apply(Transaction transaction) {
          return transaction.getYear();
       }
     }));

transactions.stream().collect(Collectors.groupingBy(Transaction::getYear));    //按年限分组
 

//多级分组
Map<Integer, Map<String, List<Transaction>>> re2 = transactions.stream().collect(Collectors.groupingBy(Transaction::getYear, Collectors.groupingBy((Transaction transaction) -> transaction.getTrader().getCity())));
Map<Integer, Map<String, List<Transaction>>> re3 = transactions.stream().collect(Collectors.groupingBy(Transaction::getYear, Collectors.groupingBy(new Function<Transaction, String>() {
@Override
public String apply(Transaction o) {
return o.getTrader().getCity();
}
})));


//注意
groupingBy收集器传递给外层收集器来实现堆积分组。进一步说传递给第一个groupingBy的第二个收集器可以是任何类型,而不一定是另一个groupingBy
Map<Integer, Long> count = transactions.stream().collect(Collectors.groupingBy(Transaction::getYear, Collectors.counting()));

将收集好的结果转换为另一种类型
Map<Integer, Transaction> re4 = transactions.stream().collect(Collectors.groupingBy(Transaction::getYear, Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparing(Transaction::getValue)), Optional::get)));



 

posted on 2018-06-12 19:53  13725566749  阅读(66)  评论(0编辑  收藏  举报