【转】java8-进阶

原文地址 http://blog.csdn.net/myherux/article/details/71855110

Java8-进阶

函数式接口

只包含一个抽象方法的接口

  • Function

    接受一个输入参数,返回一个结果。

    Function接口包含以下方法:

    定义两个比较简单的函数:times2squared

    Function times2 = e -> e * 2;
    Function squared = e -> e * e;
    
    • R apply(T t)

      执行函数

      //return 8 - > 4 * 2
      Integer a = times2.apply(4);
      System.out.println(a);
      
    • compose

      先执行参数里面的操作,然后执行调用者

      //return 32 - > 4 ^ 2 * 2
      Integer b = times2.compose(squared).apply(4);
      System.out.println(b);
      
    • andThen

      先执行调用者操作,再执行参数操作

      //return 64 - > (4 * 2) ^ 2
      Integer c = times2.andThen(squared).apply(4);
      System.out.println(c);
      
    • identity

      总是返回传入的参数本身

      //return 4
      Integer d = identity.apply(4);
      System.out.println(d);
      
  • BiFunction

    接受输入两个参数,返回一个结果

    • R apply(T t, U u)

      BiFunction add = (x, y) -> x + y;
      //return 30
      System.out.println(add.apply(10,20));
      
  • Supplier

    无参数,返回一个结果。

    • T get()

      Supplier get= () -> 10;
      //return 10
      Integer a=get.get();
      
  • Consumer

    代表了接受一个输入参数并且无返回的操作

    • void accept(T t)

      //return void
      Consumer accept=x->{};
      
  • BiConsumer

    代表了一个接受两个输入参数的操作,并且不返回任何结果

    • void accept(T t, U u)

      //return void
      BiConsumer accept=(x,y)->{};
      
  • BinaryOperator extends BiFunction

    一个作用于于两个同类型操作符的操作,并且返回了操作符同类型的结果

    定义了两个静态方法:minBy,maxBy

  • Predicate

    接受一个输入参数,返回一个布尔值结果。

    • test

      Predicate predicate=x->x.startsWith("a");
      //return ture
      System.out.println(predicate.test("abc"));
      

Stream接口

定义自己的Stream

  • collect

    collect有两个接口:

     R collect(Supplier supplier,
                  BiConsumer accumulator,
                  BiConsumer combiner);
     R collect(Collector collector);              
    
    • <1> R collect(Supplier supplier, BiConsumer accumulator, BiConsumer combiner)

      Supplier supplier是一个工厂函数,用来生成一个新的容器;

      BiConsumer accumulator也是一个函数,用来把Stream中的元素添加到结果容器中;

      BiConsumer combiner还是一个函数,用来把中间状态的多个结果容器合并成为一个(并发的时候会用到)

      Supplier> supplier = ArrayList::new;
      BiConsumer, String> accumulator = List::add;
      BiConsumer, List> combiner = List::addAll;
      
      //return [aaa1, aaa1],实现了Collectors.toCollection
      List list1 = stringCollection.stream()
              .filter(x -> x.startsWith("a"))
              .collect(supplier, accumulator, combiner);
      
    • <2> R collect(Collector collector)

      Collectors是Java已经提供好的一些工具方法:

      List stringCollection = new ArrayList<>();
      stringCollection.add("ddd2");
      stringCollection.add("aaa1");
      stringCollection.add("bbb1");
      stringCollection.add("aaa1");
      

      转换成其他集合:

      • toList

        //return [aaa1, aaa1]
        stringCollection.stream()
            .filter(x -> x.startsWith("a")).collect(Collectors.toList())
        
      • toSet

        //return [aaa1]
        stringCollection.stream()
            .filter(x -> x.startsWith("a")).collect(Collectors.toSet())
        
      • toCollection

        接口:

        public static > Collector toCollection(Supplier collectionFactory)
        

        实现:

        //return [aaa1, aaa1]
        List list = stringCollection.stream()
            .filter(x -> x.startsWith("a"))
            .collect(Collectors.toCollection(ArrayList::new));
        
      • toMap

        接口:

        public static 
        Collector> toMap(Function keyMapper,
                              Function valueMapper) 
        

        实现:

        //return {aaa1=aaa1_xu}
        Function xu = x -> x + "_xu";
        Map map = stringCollection.stream()
            .filter(x -> x.startsWith("a"))
            .distinct()
            .collect(Collectors.toMap(Function.identity(), xu));
        

      转成值:

      • averagingDouble:求平均值,Stream的元素类型为double
      • averagingInt:求平均值,Stream的元素类型为int
      • averagingLong:求平均值,Stream的元素类型为long
      • counting:Stream的元素个数
      • maxBy:在指定条件下的,Stream的最大元素
      • minBy:在指定条件下的,Stream的最小元素
      • reducing: reduce操作
      • summarizingDouble:统计Stream的数据(double)状态,其中包括count,min,max,sum和平均。
      • summarizingInt:统计Stream的数据(int)状态,其中包括count,min,max,sum和平均。
      • summarizingLong:统计Stream的数据(long)状态,其中包括count,min,max,sum和平均。
      • summingDouble:求和,Stream的元素类型为double
      • summingInt:求和,Stream的元素类型为int
      • summingLong:求和,Stream的元素类型为long

      数据分区:

      • partitioningBy

        接口:

        public static  Collector>> partitioningBy(Predicate predicate)
        
        public static 
        Collector> partitioningBy(Predicate predicate,
                                                           Collector downstream)
        

        实现:

        Predicate startA = x -> x.startsWith("a");
        //return {false=[ddd2, bbb1], true=[aaa1, aaa1]}
        Map> map2 = stringCollection.stream()
                .collect(Collectors.partitioningBy(startA));
        
        //return {false={false=[ddd2], true=[bbb1]}, true={false=[], true=[aaa1, aaa1]}}
        Predicate end1 = x -> x.endsWith("1");
        Map>> map3 = stringCollection.stream()
                .collect(Collectors.partitioningBy(startA, Collectors.partitioningBy(end1)));
        

      数据分组:

      • groupingBy

        接口:

        public static  Collector>> groupingBy(Function classifier)
        
        public static 
        Collector> groupingBy(Function classifier,
                                        Collector downstream)
        
        public static >
        Collector groupingBy(Function classifier,Supplier mapFactory,
                                Collector downstream)
        

        实现:

        //rerurn {a=[aaa1, aaa1], b=[bbb1], d=[ddd2]}
        Function stringStart = x -> String.valueOf(x.charAt(0));
        Map> map4 = stringCollection.stream()
                .collect(Collectors.groupingBy(stringStart));
        
        //rerurn {ddd2=1, bbb1=1, aaa1=2}
        Map map5 = stringCollection.stream()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        
        //rerurn {d=1, a=2, b=1}
        Map map6 = stringCollection.stream()
                .collect(Collectors.groupingBy(stringStart, LinkedHashMap::new, Collectors.counting()));
        
  • reduce

    reduce有三个接口:

    Optional reduce(BinaryOperator accumulator);
    
     U reduce(U identity,
                 BiFunction accumulator,
                 BinaryOperator combiner);
    
    T reduce(T identity, BinaryOperator accumulator);
    
    • <1> Optional reduce(BinaryOperator accumulator)

      BinaryOperator binaryOperator = (x, y) -> x + y;
      //rerurn ddd2aaa1bbb1aaa1
      String reduceStr1 = stringCollection.stream().reduce(binaryOperator).orElse("");
      
    • <2> T reduce(T identity, BinaryOperator accumulator)

      //return start:ddd2aaa1bbb1aaa1
      String reduceStr2=stringCollection.stream().reduce("start:",binaryOperator);
      
    • <3> U reduce(U identity,BiFunction accumulator,BinaryOperator combiner)

      第一个参数返回实例u,传递你要返回的U类型对象的初始化实例u

      BiFunction accumulator,负责数据的累加

      BinaryOperator combiner,负责在并行情况下最后合并每个reduce线程的结果

      List personList = new ArrayList<>();
      personList.add(new Person(10, 20));
      personList.add(new Person(20, 30));
      personList.add(new Person(30, 50));
      
      BiFunction biFunction = (x, y) -> new Person(x.getAge() + y.getAge(), x.getRate() + y.getRate());
      BinaryOperator binaryOperator1 = (x, y) -> new Person(x.getAge() + y.getAge(), x.getRate() + y.getRate());
      Person total = personList.stream().reduce(new Person(0, 0), biFunction, binaryOperator1);
      System.out.println("total:"+total);
      

你可能感兴趣的:(【转】java8-进阶)