Lamda的深入认知(九)

主题:收集器

一、需求

  1. 需要更加强大的reduce操作(收集器的实质是redcue操作的包装体)
  2. Stream的reduce方法,也可以将数据reduce到加复杂的结果上Lamda的深入认知(七),但我们更加需要库一级的reduce操作!!!

二、API布局

  1. 由Collector接口的实现类,完成reduce的算法行为。
  2. 由Collectors扮演Collector的工厂,其工厂方法中会传入lamda(通常会这样),从而产生由用户定制的Collector。
  3. 将Collector传递给Stream的collect方法
  4. collect方法为终端操作,产生结果。
  5. Demo:
        //将数据收集到Set中
        Arrays.asList(2,-3,1).stream()
                .collect(Collectors.toSet());
        
        // 将数据收集到定制的set
        Arrays.asList(2,-3,1).stream()
                .collect(Collectors.toCollection(LinkedHashSet::new));

三、常见的收集器

1. 计数统计:

Collectors.counting()

2. 简单算数统计:
  • 原型:
        Collectors.summarizingInt(ToIntFunction);
        Collectors.summarizingLong(ToLongFunction);
        Collectors.summarizingDouble(ToDoubleFunction);

        Collectors.averagingInt(ToIntFunction);
        Collectors.averagingLong(ToLongFunction);
        Collectors.averagingDouble(ToDoubleFunction);
  • demo: 统计数组中元素的个数
        int len=Arrays.asList(new int[]{1,2,8,1},new int[]{4,8,1})
                .stream()
                .collect(Collectors.summingInt(s->s.length));
3. 综合统计:
  • 原型:
Collectors.summarizingInt(ToIntFunction)
Collectors.summarizingLong(ToLongFunction)
Collectors.summarizingDouble(ToDoubleFunction)
  • demo:
IntSummaryStatistics mm = Arrays.asList(new int[]{1, 2, 8, 1}, new int[]{4, 8, 1}).stream()
                .collect(Collectors.summarizingInt(ary->ary.length));

//结果: IntSummaryStatistics{count=2, sum=7, min=3, average=3.500000, max=4}
4. 收集到集合对象中
  • 原型:
public static  Collector> toList()

public static  Collector> toSet()

public static > Collector toCollection(Supplier collectionFactory)
  • demo:
5. 找出最大及最小值
  • 原型:
public static  Collector> maxBy(Comparator comparator)
  • demo:
        //两种不同的方式
        String r1=Arrays.asList("abc","x","cdef","dd").stream()
                .collect(Collectors.maxBy((s1,s2)->s1.length()-s2.length()))
                .get();
        
        String r2=Arrays.asList("abc","x","cdef","dd").stream()
                .collect(Collectors.maxBy(Comparator.comparing(String::length)))
                .get();
        //结果:cdef
6. 连接操作
  • 原型:
public static Collector joining(CharSequence delimiter)
  • demo:
        String r3=Arrays.asList("abc","x","cdef","dd").stream()
                .collect(Collectors.joining("-"));
        //结果:abc-x-cdef-dd

7. 广义reduce: 功能最强大的Collector(除自定制Collector外)

  • 原型:
public static  Collector reducing(U identity, 
  Function mapper, BinaryOperator op)
  • demo:统计字符的总个数
        int totalLen1=Arrays.asList("abc","x","cdef","dd").stream()
                .collect(Collectors.reducing(0,s->s.length(),(a,b)->a+b));
        int totalLen2=Arrays.asList("abc","x","cdef","dd").stream()
                .collect(Collectors.reducing(0,String::length,Integer::sum));
        //result:10

你可能感兴趣的:(Lamda的深入认知(九))