一、收集器Collector

//T:表示流中每个元素的类型。 A:表示中间结果容器的类型。 R:表示最终返回的结果类型。
public interface Collector<T, A, R> {

    Supplier<A> supplier()//生成容器

    BiConsumer<A,T>    accumulator()//是添加元素

    BinaryOperator<A> combiner()//是合并容器

    Function<A,R>finisher()///是输出的结果

    Set<Collector.Characteristics>    characteristics()//返回Set的Collector.Characteristics指示此收集器的特征。

    //返回一个新的Collector由给定的描述supplier, accumulator,combiner,和finisher功能。
    static <T,A,R> Collector<T,A,R> of(Supplier<A> supplier, 
                                        BiConsumer<A,T> accumulator,
                                        BinaryOperator<A> combiner,
                                        Function<A,R> finisher,
                                        Collector.Characteristics... characteristics)


    //返回一个新的Collector由给定的描述supplier, accumulator和combiner功能。
    static <T,R> Collector<T,R,R>    of(Supplier<R> supplier, 
                                       BiConsumer<R,T> accumulator, 
                                       BinaryOperator<R> combiner, 
                                       Collector.Characteristics... characteristics)

}

二、收集器工厂Collectors

public final class Collectors extends Object

Collectors作为Stream的collect方法的参数,Collector是一个接口,它是一个可变的汇聚操作,将输入元素累计到一个可变的结果容器中;它会在所有元素都处理完毕后,将累积的结果转换为一个最终的表示(这是一个可选操作);

Collectors本身提供了关于Collector的常见汇聚实现,Collectors的内部类CollectorImpl实现了Collector接口,Collectors本身实际上是一个
工厂。

2.1 变成ConcurrentMap

//返回将Collector元素累积到其中 ConcurrentMap的并发函数,其键和值是将提供的映射函数应用于输入元素的结果。
static <T,K,U> Collector<T,?,ConcurrentMap<K,U>>    toConcurrentMap(Function<? super T,? extends K> keyMapper, 
                                                                      Function<? super T,? extends U> valueMapper)

//返回将Collector元素累积到其中 ConcurrentMap的并发函数,其键和值是将提供的映射函数应用于输入元素的结果。
static <T,K,U> Collector<T,?,ConcurrentMap<K,U>>    toConcurrentMap(Function<? super T,? extends K> keyMapper, 
                                                                      Function<? super T,? extends U> valueMapper, 
                                                                      BinaryOperator<U> mergeFunction)
//返回将Collector元素累积到其中 ConcurrentMap的并发函数,其键和值是将提供的映射函数应用于输入元素的结果。
static <T,K,U,M extends ConcurrentMap<K,U>> Collector<T,?,M>    toConcurrentMap(
                            Function<? super T,? extends K> keyMapper, 
                            Function<? super T,? extends U> valueMapper, 
                            BinaryOperator<U> mergeFunction, 
                            Supplier<M> mapSupplier
                     )

2.2 变成Map

static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper, 
                                             Function<? super T,? extends U> valueMapper)

//1、当key重复时,会抛出异常:java.lang.IllegalStateException: Duplicate key 
//2、当value为null时,会抛出异常:java.lang.NullPointerException

案例:

List<Person>integerList=newArrayList<>();
integerList.add(new Person("a",3));
integerList.add(new Person("b",3));
integerList.add(new Person("c",3));
integerList.add(new Person("d",2));
integerList.add(new Person("e",2));
integerList.add(new Person("f",2));
Mapmap=integerList.stream().collect(Collectors.toMap(Person::getName,Person::getAge));
System.out.println(map);//{a=3, b=3, c=3, d=2, e=2, f=2}
//第三个参数用在key值冲突的情况下:如果新元素产生的key在Map中已经出现过了,第三个参数就会定义解决的办法。
static <T,K,U> Collector<T,?,Map<K,U>> toMap(  Function<? super T,? extends K> keyMapper, 
                                               Function<? super T,? extends U> valueMapper, 
                                               BinaryOperator<U> mergeFunction)

案例:

List<Person> integerList = new ArrayList<>();
integerList.add(new Person("a",3));
integerList.add(new Person("b",3));
integerList.add(new Person("c",3));
integerList.add(new Person("d",2));
integerList.add(new Person("e",2));
integerList.add(new Person("e",3));

Collections.sort(integerList,comparator);
System.out.println(integerList);*/
Map map =integerList.stream().collect(Collectors.toMap(Person::getName,Person::getAge,(a,b)->a b));
System.out.println(map);//{a=3, b=3, c=3, d=2, e=5}
//返回将Collector元素累积到 Map其键中的值,其值是将提供的映射函数应用于输入元素的结果。
static <T,K,U,M extends Map<K,U>> Collector<T,?,M>  toMap( Function<? super T,? extends K> keyMapper, 
                                                            Function<? super T,? extends U> valueMapper, 
                                                            BinaryOperator<U> mergeFunction, 
                                                            Supplier<M> mapSupplier)

2.3 变成Collection

static <T> Collector<T,?,List<T>> toList()
static <T> Collector<T,?,Set<T>>  toSet()  
//自定义 
static <T,C extends Collection<T>>  Collector<T,?,C>  toCollection(Supplier<C> collectionFactory)

案例:

List<Person> integerList = new ArrayList<>();
integerList.add(new Person("a",3));
integerList.add(new Person("b",3));
integerList.add(new Person("c",3));
integerList.add(new Person("d",2));
integerList.add(new Person("e",2));
integerList.add(new Person("e",3));
List<Integer> list= integerList.stream().map(Person::getAge).collect(Collectors.toList());
System.out.println(list);//[3, 3, 3, 2, 2, 3]
System.out.println(list.getClass());//class java.util.ArrayList
Set<Integer>set=integerList.stream().map(Person::getAge).collect(Collectors.toSet());
System.out.println(set);//[2, 3]
System.out.println(set.getClass());//class java.util.HashSet
LinkedList<Integer>linkedList=integerList.stream().map(Person::getAge).collect(Collectors.toCollection(LinkedList::new));
System.out.println(linkedList);//[3, 3, 3, 2, 2, 3]
System.out.println(linkedList.getClass());//class java.util.LinkedList

2.4 变成String

static Collector<CharSequence,?,String>    joining()
//delimiter分隔符连接
static Collector<CharSequence,?,String>    joining(CharSequence delimiter) 
//prefix前缀
//suffix后缀
static Collector<CharSequence,?,String>    joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

案例:

List<Person> integerList = newArrayList<>();
integerList.add(new Person("a",3));
integerList.add(new Person("b",3));
integerList.add(new Person("c",3));
integerList.add(new Person("d",2));
integerList.add(new Person("e",2));
integerList.add(new Person("e",3));
Stringlist = integerList.stream().map(Person::getName).collect(Collectors.joining());
System.out.println(list);//abcdee
Stringset = integerList.stream().map(Person::getName).collect(Collectors.joining(","));
System.out.println(set);//a,b,c,d,e,e
StringlinkedList = integerList.stream().map(Person::getName).collect(Collectors.joining(",","(",")"));
System.out.println(linkedList);//(a,b,c,d,e,e)

2.5 计算最值

static <T> Collector<T,?,Optional<T>>  maxBy(Comparator<? super T> comparator) 
static <T> Collector<T,?,Optional<T>>  minBy(Comparator<? super T> comparator)

案例:

List<Person> integerList = new ArrayList<>();
integerList.add(new Person("a",1));
integerList.add(new Person("b",2));
integerList.add(new Person("c",3));
integerList.add(new Person("d",4));
integerList.add(new Person("e",5));
integerList.add(new Person("e",6));
Optional<Person> person = integerList.stream().collect(Collectors.maxBy(Comparator.comparing(Person::getAge)));
System.out.println(person.get());//Person{name='e',age='6'}

2.6 平均值

static <T> Collector<T,?,Double> averagingDouble(ToDoubleFunction<? super T> mapper)
static <T> Collector<T,?,Double> averagingInt(ToIntFunction<? super T> mapper)
static <T> Collector<T,?,Double> averagingLong(ToLongFunction<? super T> mapper)

案例:
 

List<Person> integerList = new ArrayList<>();
integerList.add(new Person("a",1));
integerList.add(new Person("b",1));
integerList.add(new Person("c",1));
integerList.add(new Person("d",1));
integerList.add(new Person("e",1));
integerList.add(new Person("e",1));
double number=integerList.stream().collect(Collectors.averagingDouble(Person::getAge));
System.out.println(number);//1.0

2.7 统计数据

static <T> Collector<T,?,DoubleSummaryStatistics> summarizingDouble(ToDoubleFunction<? super T> mapper)
static <T> Collector<T,?,IntSummaryStatistics>     summarizingInt(ToIntFunction<? super T> mapper) 
static <T> Collector<T,?,LongSummaryStatistics> summarizingLong(ToLongFunction<? super T> mapper)

DoubleSummaryStatistics,IntSummaryStatistics,LongSummaryStatistics 用于收集统计数据(如计数,最小值,最大值,总和和平均值)的状态对象。
此实现不是线程安全的。但是,Collectors.toXXXStatistics()在并行流上使用是安全的 ,因为并行实现Stream.collect() 提供了必要的分区,隔离和合并结果,以实现安全有效的并行执行。

他们的方法如下:

void accept(int value)//添加一个值
void combine(IntSummaryStatistics other)//将另一个的状态合并IntSummaryStatistics到这个状态中。
double getAverage()//算术平均值,如果没有记录值,则返回零。
long getCount()//返回记录的值的计数。
int getMax()//返回记录的最大值,或者Integer.MIN_VALUE没有记录值。
int getMin()//返回记录的最小值,或者Integer.MAX_VALUE没有记录值。
long getSum()//返回记录的值的总和,如果没有记录值,则返回零。
String toString()//返回对象的字符串表示形式。

案例:

List<Person> integerList = new ArrayList<>();
integerList.add(new Person("a",1));
integerList.add(new Person("b",2));
integerList.add(new Person("c",3));
integerList.add(new Person("d",4));
integerList.add(new Person("e",5));
integerList.add(new Person("e",6));

DoubleSummaryStatistics number = integerList.stream().collect(Collectors.summarizingDouble(Person::getAge));
System.out.println(number.getMax());//6
System.out.println(number.getMin());//1.0
System.out.println(number.getSum());//21.0
System.out.println(number.getAverage());//3.5
number.accept(100);
System.out.println(number.getMax());//100.0

2.8 求和

static <T> Collector<T,?,Double> summingDouble(ToDoubleFunction<? super T> mapper)    
static <T> Collector<T,?,Integer> summingInt(ToIntFunction<? super T> mapper)    
static <T> Collector<T,?,Long>    summingLong(ToLongFunction<? super T> mapper)

2.9 reducing函数

//op 缩减的函数
static <T> Collector<T,?,Optional<T>> reducing(BinaryOperator<T> op)     
//identity储存器初始值
static <T> Collector<T,?,T> reducing(T identity, BinaryOperator<T> op)
//mapper作用的数值
static <T,U> Collector<T,?,U>    reducing(U identity, Function<? super T,? extends U> mapper, BinaryOperator<U> op)

案例:

List<Person> integerList = new ArrayList<>();
integerList.add(new Person("a",1));
integerList.add(new Person("b",0));
integerList.add(new Person("c",0));
integerList.add(new Person("d",0));
integerList.add(new Person("e",0));
integerList.add(new Person("e",0));

Integernumber = integerList.stream().collect(Collectors.reducing(1,Person::getAge,(a,b)->a b));
System.out.println(number);//2

2.10 计数

//返回Collector类型的接受元素,T用于计算输入元素的数量。
static <T> Collector<T,?,Long>    counting()

2.11 分组-变成map

//classifier分组依据函数
static <T,K> Collector<T,?,Map<K,List<T>>> groupingBy(Function<? super T,? extends K> classifier)

案例:

List<Person> integerList = new ArrayList<>();
integerList.add(new Person("a",1));
integerList.add(new Person("a",2));
integerList.add(new Person("a",3));
integerList.add(new Person("b",4));
integerList.add(new Person("b",5));
integerList.add(new Person("b",6));
    
Map map =i ntegerList.stream().collect(Collectors.groupingBy(Person::getName));
System.out.println(map);
{
a=[Person{name='a', age='1'}, Person{name='a', age='2'}, Person{name='a', age='3'}], 
b=[Person{name='b', age='4'}, Person{name='b', age='5'}, Person{name='b', age='6'}]
}
//downstream将小组内对象进行处理
static <T,K,A,D> Collector<T,?,Map<K,D>>    groupingBy(Function<? super T,? extends K> classifier, 
                                                        Collector<? super T,A,D> downstream)


//mapFactory中间操作
static <T,K,D,A,M extends Map<K,D>> Collector<T,?,M>  groupingBy(Function<? super T,? extends K> classifier, 
                                                                   Supplier<M> mapFactory, 
                                                                   Collector<? super T,A,D> downstream)

案例:

List<Person> integerList = newArrayList<>();
integerList.add(new Person("a",1));
integerList.add(new Person("a",2));
integerList.add(new Person("a",3));
integerList.add(new Person("b",4));
integerList.add(new Person("b",5));
integerList.add(new Person("b",6));
Map map= i ntegerList.stream()
                    .collect(Collectors.groupingBy(Person::getName,Collectors.reducing(0,Person::getAge,(a,b)->a b)));
System.out.println(map);//{a=6, b=15}
Map map = integerList.stream()
                    .collect(Collectors.groupingBy(Person::getName,TreeMap::new,Collectors.reducing(0,Person::getAge,(a,b)->a b)));
System.out.println(map.getClass());//classjava.util.TreeMap

2.12 分组-变成ConcurrentMap

static <T,K> Collector<T,?,ConcurrentMap<K,List<T>>>    groupingByConcurrent(Function<? super T,? extends K> classifier)
static <T,K,A,D> Collector<T,?,ConcurrentMap<K,D>>    groupingByConcurrent(Function<? super T,? extends K> classifier, 
                                                                           Collector<? super T,A,D> downstream)
static <T,K,A,D,M extends ConcurrentMap<K,D>> Collector<T,?,M> groupingByConcurrent(Function<? super T,? extends K> classifier, 
                                                                                       Supplier<M> mapFactory, 
                                                                                       Collector<? super T,A,D> downstream)

2.13 分割流

//predicate分区的依据
static <T> Collector<T,?,Map<Boolean,List<T>>>     partitioningBy(Predicate<? super T> predicate)

static <T,D,A> Collector<T,?,Map<Boolean,D>>    partitioningBy(Predicate<? super T> predicate, Collector<? super T,A,D> downstream)

2.14 收集器

通过在累积之前将映射函数应用于每个输入Collector元素,使类型的接受元素适应一个接受类型的U元素T。

static <T,U,A,R> Collector<T,?,R>    mapping(Function<? super T,? extends U> mapper, Collector<? super U,A,R> downstream)

案例:

List<Person> integerList = new ArrayList<>();
integerList.add(new Person("a",1));
integerList.add(new Person("a",2));
integerList.add(new Person("a",3));
integerList.add(new Person("b",4));
integerList.add(new Person("b",5));
integerList.add(new Person("b",6));

List list = integerList.stream().collect(Collectors.mapping(Person::getName,Collectors.toList()));

System.out.println(list);//[a, a, a, b, b, b]

2.15 收集之后继续做一些处理

static <T,A,R,RR> Collector<T,A,RR>    collectingAndThen(Collector<T,A,R> downstream, Function<R,RR> finisher)

到此这篇关于java收集器Collector详情的文章就介绍到这了,更多相关java收集器 内容请搜索Devmax以前的文章或继续浏览下面的相关文章希望大家以后多多支持Devmax!

java收集器Collector案例汇总的更多相关文章

  1. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  2. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  3. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  4. Java实现世界上最快的排序算法Timsort的示例代码

    Timsort 是一个混合、稳定的排序算法,简单来说就是归并排序和二分插入排序算法的混合体,号称世界上最好的排序算法。本文将详解Timsort算法是定义与实现,需要的可以参考一下

  5. Java日期工具类的封装详解

    在日常的开发中,我们难免会对日期格式化,对日期进行计算,对日期进行校验,为了避免重复写这些琐碎的逻辑,我这里封装了一个日期工具类,方便以后使用,直接复制代码到项目中即可使用,需要的可以参考一下

  6. Java设计模式之模板方法模式Template Method Pattern详解

    在我们实际开发中,如果一个方法极其复杂时,如果我们将所有的逻辑写在一个方法中,那维护起来就很困难,要替换某些步骤时都要重新写,这样代码的扩展性就很差,当遇到这种情况就要考虑今天的主角——模板方法模式

  7. Java 中 Class Path 和 Package的使用详解

    这篇文章主要介绍了Java 中 Class Path和Package的使用详解,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的朋友可以参考一下

  8. java SpringBoot 分布式事务的解决方案(JTA+Atomic+多数据源)

    这篇文章主要介绍了java SpringBoot 分布式事务的解决方案(JTA+Atomic+多数据源),文章围绕主题展开详细的内容介绍,具有一定的参考价值,感兴趣的小伙伴可以参考一下

  9. Java一维数组和二维数组元素默认初始化值的判断方式

    这篇文章主要介绍了Java一维数组和二维数组元素默认初始化值的判断方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  10. java实现emqx设备上下线监听详解

    这篇文章主要为大家介绍了java实现emqx设备上下线监听详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

随机推荐

  1. 基于EJB技术的商务预订系统的开发

    用EJB结构开发的应用程序是可伸缩的、事务型的、多用户安全的。总的来说,EJB是一个组件事务监控的标准服务器端的组件模型。基于EJB技术的系统结构模型EJB结构是一个服务端组件结构,是一个层次性结构,其结构模型如图1所示。图2:商务预订系统的构架EntityBean是为了现实世界的对象建造的模型,这些对象通常是数据库的一些持久记录。

  2. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  3. Mybatis分页插件PageHelper手写实现示例

    这篇文章主要为大家介绍了Mybatis分页插件PageHelper手写实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  4. (jsp/html)网页上嵌入播放器(常用播放器代码整理)

    网页上嵌入播放器,只要在HTML上添加以上代码就OK了,下面整理了一些常用的播放器代码,总有一款适合你,感兴趣的朋友可以参考下哈,希望对你有所帮助

  5. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  6. Java异常Exception详细讲解

    异常就是不正常,比如当我们身体出现了异常我们会根据身体情况选择喝开水、吃药、看病、等 异常处理方法。 java异常处理机制是我们java语言使用异常处理机制为程序提供了错误处理的能力,程序出现的错误,程序可以安全的退出,以保证程序正常的运行等

  7. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  8. 面试突击之跨域问题的解决方案详解

    跨域问题本质是浏览器的一种保护机制,它的初衷是为了保证用户的安全,防止恶意网站窃取数据。那怎么解决这个问题呢?接下来我们一起来看

  9. Mybatis-Plus接口BaseMapper与Services使用详解

    这篇文章主要为大家介绍了Mybatis-Plus接口BaseMapper与Services使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  10. mybatis-plus雪花算法增强idworker的实现

    今天聊聊在mybatis-plus中引入分布式ID生成框架idworker,进一步增强实现生成分布式唯一ID,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部