一、收集器Collector
//T:表示流中每个元素的类型。 A:表示中间结果容器的类型。 R:表示最终返回的结果类型。 public interface Collector{ Supplier supplier()//生成容器 BiConsumer accumulator()//是添加元素 BinaryOperator combiner()//是合并容器 Functionfinisher()///是输出的结果 Set characteristics()//返回Set的Collector.Characteristics指示此收集器的特征。 //返回一个新的Collector由给定的描述supplier, accumulator,combiner,和finisher功能。 static Collector of(Supplier supplier, BiConsumer accumulator, BinaryOperator combiner, Function finisher, Collector.Characteristics... characteristics) //返回一个新的Collector由给定的描述supplier, accumulator和combiner功能。 static Collector of(Supplier supplier, BiConsumer accumulator, BinaryOperator 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的并发函数,其键和值是将提供的映射函数应用于输入元素的结果。 staticCollector > toConcurrentMap(Function super T,? extends K> keyMapper, Function super T,? extends U> valueMapper) //返回将Collector元素累积到其中 ConcurrentMap的并发函数,其键和值是将提供的映射函数应用于输入元素的结果。 static Collector > toConcurrentMap(Function super T,? extends K> keyMapper, Function super T,? extends U> valueMapper, BinaryOperator mergeFunction) //返回将Collector元素累积到其中 ConcurrentMap的并发函数,其键和值是将提供的映射函数应用于输入元素的结果。 static > Collector toConcurrentMap( Function super T,? extends K> keyMapper, Function super T,? extends U> valueMapper, BinaryOperator mergeFunction, Supplier mapSupplier )
2.2 变成Map
staticCollector > 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
案例:
ListintegerList=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中已经出现过了,第三个参数就会定义解决的办法。 staticCollector > toMap( Function super T,? extends K> keyMapper, Function super T,? extends U> valueMapper, BinaryOperator mergeFunction)
案例:
ListintegerList = 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> Collector toMap( Function super T,? extends K> keyMapper, Function super T,? extends U> valueMapper, BinaryOperator mergeFunction, Supplier mapSupplier)
2.3 变成Collection
staticCollector > toList() static Collector > toSet() //自定义 static > Collector toCollection(Supplier collectionFactory)
案例:
ListintegerList = 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 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 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 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 Collectorjoining() //delimiter分隔符连接 static Collector joining(CharSequence delimiter) //prefix前缀 //suffix后缀 static Collector joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
案例:
ListintegerList = 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 计算最值
staticCollector > maxBy(Comparator super T> comparator) static Collector > minBy(Comparator super T> comparator)
案例:
ListintegerList = 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 = integerList.stream().collect(Collectors.maxBy(Comparator.comparing(Person::getAge))); System.out.println(person.get());//Person{name='e',age='6'}
2.6 平均值
staticCollector averagingDouble(ToDoubleFunction super T> mapper) static Collector averagingInt(ToIntFunction super T> mapper) static Collector averagingLong(ToLongFunction super T> mapper)
案例:
ListintegerList = 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 统计数据
staticCollector summarizingDouble(ToDoubleFunction super T> mapper) static Collector summarizingInt(ToIntFunction super T> mapper) static Collector 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()//返回对象的字符串表示形式。
案例:
ListintegerList = 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 求和
staticCollector summingDouble(ToDoubleFunction super T> mapper) static Collector summingInt(ToIntFunction super T> mapper) static Collector summingLong(ToLongFunction super T> mapper)
2.9 reducing函数
//op 缩减的函数 staticCollector > reducing(BinaryOperator op) //identity储存器初始值 static Collector reducing(T identity, BinaryOperator op) //mapper作用的数值 static Collector reducing(U identity, Function super T,? extends U> mapper, BinaryOperator op)
案例:
ListintegerList = 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用于计算输入元素的数量。 staticCollector counting()
2.11 分组-变成map
//classifier分组依据函数 staticCollector >> groupingBy(Function super T,? extends K> classifier)
案例:
ListintegerList = 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将小组内对象进行处理 staticCollector > groupingBy(Function super T,? extends K> classifier, Collector super T,A,D> downstream) //mapFactory中间操作 static > Collector groupingBy(Function super T,? extends K> classifier, Supplier mapFactory, Collector super T,A,D> downstream)
案例:
ListintegerList = 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
staticCollector >> groupingByConcurrent(Function super T,? extends K> classifier) static Collector > groupingByConcurrent(Function super T,? extends K> classifier, Collector super T,A,D> downstream) static > Collector groupingByConcurrent(Function super T,? extends K> classifier, Supplier mapFactory, Collector super T,A,D> downstream)
2.13 分割流
//predicate分区的依据 staticCollector >> partitioningBy(Predicate super T> predicate) static Collector > partitioningBy(Predicate super T> predicate, Collector super T,A,D> downstream)
2.14 收集器
通过在累积之前将映射函数应用于每个输入Collector元素,使类型的接受元素适应一个接受类型的U元素T。
staticCollector mapping(Function super T,? extends U> mapper, Collector super U,A,R> downstream)
案例:
ListintegerList = 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 收集之后继续做一些处理
staticCollector collectingAndThen(Collector downstream, Function finisher)
到此这篇关于java收集器Collector详情的文章就介绍到这了,更多相关java收集器 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!