Collectors
Collectors它是个工具类,提供了很多静态方法来返回Collector。通常作为Stream.collect()方法的入参,来实现更多的功能。
API分类
求平均值
static <T> Collector<T,?,Double>
|
averagingDouble(ToDoubleFunction<? super T> mapper)
Returns a |
static <T> Collector<T,?,Double>
|
averagingInt(ToIntFunction<? super T> mapper)
Returns a |
static <T> Collector<T,?,Double>
|
averagingLong(ToLongFunction<? super T> mapper)
Returns a |
统计
static <T> Collector<T,?,Long>
|
counting()
Returns a |
分组
static <T,K> Collector<T,?,Map<K,List<T>>>
|
groupingBy(Function<? super T,? extends K> classifier)
Returns a |
static <T,K,A,D> Collector<T,?,Map<K,D>>
|
groupingBy(Function<? super T,? extends K> classifier, Collector<? super T,A,D> downstream)
Returns a |
static <T,K,D,A,M extends Map<K,D>>
|
groupingBy(Function<? super T,? extends K> classifier, Supplier<M> mapFactory, Collector<? super T,A,D> downstream)
Returns a |
static <T,K> Collector<T,?,ConcurrentMap<K,List<T>>>
|
groupingByConcurrent(Function<? super T,? extends K> classifier)
Returns a concurrent |
static <T,K,A,D> Collector<T,?,ConcurrentMap<K,D>>
|
groupingByConcurrent(Function<? super T,? extends K> classifier, Collector<? super T,A,D> downstream)
Returns a concurrent |
static <T,K,A,D,M extends ConcurrentMap<K,D>>
|
groupingByConcurrent(Function<? super T,? extends K> classifier, Supplier<M> mapFactory, Collector<? super T,A,D> downstream)
Returns a concurrent |
字符串操作
static Collector<CharSequence,?,String>
|
joining()
Returns a |
static Collector<CharSequence,?,String>
|
joining(CharSequence delimiter)
Returns a |
static Collector<CharSequence,?,String>
|
joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
Returns a |
mapping
类似Stream.map()方法
static <T,U,A,R> Collector<T,?,R>
|
mapping(Function<? super T,? extends U> mapper, Collector<? super U,A,R> downstream)
Adapts a |
最值
static <T> Collector<T,?,Optional<T>>
|
maxBy(Comparator<? super T> comparator)
Returns a |
static <T> Collector<T,?,Optional<T>>
|
minBy(Comparator<? super T> comparator)
Returns a |
分区
返回一个Map,key值为true或false,value为满足对应条件的数据。
static <T> Collector<T,?,Map<Boolean,List<T>>>
|
partitioningBy(Predicate<? super T> predicate)
Returns a |
static <T,D,A> Collector<T,?,Map<Boolean,D>>
|
partitioningBy(Predicate<? super T> predicate, Collector<? super T,A,D> downstream)
Returns a |
规约
static <T> Collector<T,?,Optional<T>>
|
reducing(BinaryOperator<T> op)
Returns a |
static <T> Collector<T,?,T>
|
reducing(T identity, BinaryOperator<T> op)
Returns a |
static <T,U> Collector<T,?,U>
|
reducing(U identity, Function<? super T,? extends U> mapper, BinaryOperator<U> op)
Returns a |
求和
static <T> Collector<T,?,Double>
|
summingDouble(ToDoubleFunction<? super T> mapper)
Returns a |
static <T> Collector<T,?,Integer>
|
summingInt(ToIntFunction<? super T> mapper)
Returns a |
static <T> Collector<T,?,Long>
|
summingLong(ToLongFunction<? super T> mapper)
Returns a |
summarizing
返回各种SummarayStatistics对象,通过这些对象可以获取最大值、最小值、平均值、计数等。
static <T> Collector<T,?,DoubleSummaryStatistics>
|
summarizingDouble(ToDoubleFunction<? super T> mapper)
Returns a |
static <T> Collector<T,?,IntSummaryStatistics>
|
summarizingInt(ToIntFunction<? super T> mapper)
Returns a |
static <T> Collector<T,?,LongSummaryStatistics>
|
summarizingLong(ToLongFunction<? super T> mapper)
Returns a |
集合转换
可以将Stream流转换成List、Map、Set集合。
static <T,C extends Collection<T>>
|
toCollection(Supplier<C> collectionFactory)
Returns a |
static <T,K,U> Collector<T,?,ConcurrentMap<K,U>>
|
toConcurrentMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)
Returns a concurrent |
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)
Returns a concurrent |
static <T,K,U,M extends ConcurrentMap<K,U>>
|
toConcurrentMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier)
Returns a concurrent |
static <T> Collector<T,?,List<T>>
|
toList()
Returns a |
static <T,K,U> Collector<T,?,Map<K,U>>
|
toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper)
Returns a |
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)
Returns a |
static <T,K,U,M extends Map<K,U>>
|
toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier)
Returns a |
static <T> Collector<T,?,Set<T>>
|
toSet()
Returns a |
案例
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;public class CollectorsTest2 {public static void main(String[] args) {List<Book> list = new ArrayList<>();list.add(new Book("Core Java", 200,30));list.add(new Book("Learning Freemarker", 150, 50));list.add(new Book("Spring MVC", 300, 50));
// list.add(new Book("Spring MVC", 300, 50));// averagingDouble方法ToDoubleFunction<Book> toDoubleFunction = new ToDoubleFunction<Book>() {@Overridepublic double applyAsDouble(Book book) {return book.getPrice();}};Double averagingDouble = list.stream().collect(Collectors.averagingDouble(toDoubleFunction));System.out.println(averagingDouble);// averagingIntDouble averagingInt = list.stream().collect(Collectors.averagingInt(Book::getCount));System.out.println(averagingInt);// averagingLongDouble averagingLong = list.stream().collect(Collectors.averagingLong(Book::getCount));System.out.println(averagingLong);// collectingAndThenInteger andThen = list.stream().collect(Collectors.collectingAndThen(Collectors.groupingBy(Book::getName), map -> map.size()));System.out.println(andThen);// `counting()`Long count = list.stream().collect(Collectors.counting());System.out.println(count);// groupingByMap<String, List<Book>> groupingBy = list.stream().collect(Collectors.groupingBy(Book::getName));System.out.println(groupingBy); // {Learning Freemarker=[Book{name='Learning Freemarker', price=150.0, count=50}], Core Java=[Book{name='Core Java', price=200.0, count=30}], Spring MVC=[Book{name='Spring MVC', price=300.0, count=50}, Book{name='Spring MVC', price=300.0, count=50}]}Map<String, Long> groupingBy_Reduce = list.stream().collect(Collectors.groupingBy(Book::getName, Collectors.counting()));System.out.println(groupingBy_Reduce); // {Learning Freemarker=1, Core Java=1, Spring MVC=2}HashMap<String, Long> groupingBy_ResultMap_Reduce = list.stream().collect(Collectors.groupingBy(Book::getName, HashMap::new, Collectors.counting()));System.out.println(groupingBy_ResultMap_Reduce); // {Learning Freemarker=1, Core Java=1, Spring MVC=2}// groupingByConcurrentConcurrentMap<String, List<Book>> concurrentGroupBy = list.stream().collect(Collectors.groupingByConcurrent(Book::getName));ConcurrentMap<String, Long> concurrentGroupBy_Reduce = list.stream().collect(Collectors.groupingByConcurrent(Book::getName, Collectors.counting()));ConcurrentHashMap<String, Long> concurrentGroupBy_ResultMap_Reduce = list.stream().collect(Collectors.groupingByConcurrent(Book::getName, ConcurrentHashMap::new, Collectors.counting()));// joiningString joining = list.stream().map(Book::getName).collect(Collectors.joining(","));System.out.println(joining); // Core Java,Learning Freemarker,Spring MVC,Spring MVC// mappingString mapping = list.stream().collect(Collectors.mapping(Book::getName, Collectors.joining(",")));System.out.println(mapping); // Core Java,Learning Freemarker,Spring MVC,Spring MVC// maxByOptional<Book> maxBy = list.stream().collect(Collectors.maxBy(Comparator.comparing(Book::getPrice)));maxBy.ifPresent(System.out::println); // Book{name='Spring MVC', price=300.0, count=50}// minByOptional<String> minBy = list.stream().map(Book::getName).collect(Collectors.maxBy(String::compareTo));minBy.ifPresent(System.out::println); // Spring MVC// partitioningByMap<Boolean, List<Book>> partitioningBy = list.stream().collect(Collectors.partitioningBy(book -> book.getPrice() > 200));System.out.println(partitioningBy); // {false=[Book{name='Core Java', price=200.0, count=30}, Book{name='Learning Freemarker', price=150.0, count=50}], true=[Book{name='Spring MVC', price=300.0, count=50}, Book{name='Spring MVC', price=300.0, count=50}]}Map<Boolean, Long> partitioningBy_Reduce = list.stream().collect(Collectors.partitioningBy(book -> book.getPrice() > 200, Collectors.counting()));System.out.println(partitioningBy_Reduce); // {false=2, true=2}// reducingOptional<Book> reducing = list.stream().collect(Collectors.reducing(BinaryOperator.maxBy(Comparator.comparing(Book::getPrice))));reducing.ifPresent(System.out::println); // Book{name='Spring MVC', price=300.0, count=50}// summarizingIntSummaryStatistics intSummaryStatistics = list.stream().collect(Collectors.summarizingInt(Book::getCount));double average = intSummaryStatistics.getAverage();long count1 = intSummaryStatistics.getCount();int max = intSummaryStatistics.getMax();int min = intSummaryStatistics.getMin();// toConcurrentMapConcurrentMap<String, Integer> toConcurrentMap = list.stream().collect(Collectors.toConcurrentMap(Book::getName, Book::getCount));System.out.println(toConcurrentMap);// toListList<Book> toList = list.stream().collect(Collectors.toList());// toMapMap<String, Integer> toMap = list.stream().collect(Collectors.toMap(Book::getName, Book::getCount));}static class Book {private String name;private double price;private int count;public Book(String name, double price, int count) {this.name = name;this.price = price;this.count = count;}public String getName() {return name;}public void setName(String name) {this.name = name;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}public int getCount() {return count;}public void setCount(int count) {this.count = count;}@Overridepublic String toString() {return "Book{" +"name='" + name + '\'' +", price=" + price +", count=" + count +'}';}}
}
希望能帮助大家熟悉Collectors的使用。
Collectors相关推荐
- java8 group by_java8新特性Java 8 – Stream Collectors groupingBy 示例 - Java教程
在这篇教程中,将向你展示如何使用Java 8 Stream的Collectors,来对一个List进行分组,计算个数,求和以及排序. 1. Group By, Count and Sort 1.1 对 ...
- collectors排序_Collectors.groupingBy分组后的排序问题
默认groupingBy代码里会生成一个HashMap(hashMap是无序的,put的顺序与get的顺序不一致) HashMap是无序的,HashMap在put的时候是根据key的hashcode进 ...
- js 中转换成list集合_java stream中Collectors的用法
简介 在java stream中,我们通常需要将处理后的stream转换成集合类,这个时候就需要用到stream.collect方法.collect方法需要传入一个Collector类型,要实现Col ...
- java 返回double数组_java-如何使用Collectors.averagingDouble计算双精度数组的均值?
我不明白为什么以下代码无法编译: import java.util.Arrays; import java.util.stream.Collectors; public class AppMain { ...
- Stream流与Lambda表达式(三) 静态工厂类Collectors
/*** @author 陈杨*/@SpringBootTest @RunWith(SpringRunner.class) public class CollectorsDetail {private ...
- Java 8 - 收集器Collectors
文章目录 Pre 简介 收集器用作高级归约 预定义收集器 Pre 我们前面学到了,流可以用类似于数据库的操作帮助你处理集合. 它们支持两种类型的操作: 中间操作(如 filter 或 map ) 终端 ...
- 【备忘录】Product cost collectors – 成本收集器
以生产角度来划分: 流程制造 - Product Cost by Period 离散制造 - Product Cost by Period & Product Cost by Order 这里 ...
- java 相加的函数_Java8 Collectors求和功能的自定义扩展操作
业务中需要将一组数据分类后收集总和,原本可以使用Collectors.summingInt(),但是我们的数据源是BigDecimal类型的,而Java8原生只提供了summingInt.summin ...
- 用流收集数据Collectors的用法介绍分组groupingBy、分区partitioningBy(一)
文章目录 一.收集器简介 二.归约和汇总 1.查找流中最大值和最小值Collectors.maxBy和,Collectors.minBy 2.汇总 3.连接字符串 4.广义归约汇总 三.分组 1.多级 ...
- 【Java代码】实现字符串转数据库的 inStr【使用 JDK8 stream.collect(Collectors.joining(delimiter, prefix, suffix)) 实现】
why 有不少这样的情况,前端会传筛选条件,给到后端的时候是个 conditionStr ,如果您用的是 mybatis-plus 的 API 那么直接 split 一下就可以使用,如果不是,那就需要 ...
最新文章
- 手把手教你AndroidStudio多渠道打包
- 内存首地址为1000h_C++虚继承,菱形继承,内存分布
- 核心概念——节点/边/Combo——内置节点——Diamond
- 大数开方(Java版)
- Django 聚合查询
- 一个免费调用的OData服务,无需用户名密码,适用于SAP UI5的学习
- RTT的IPC机制篇——信号
- 【Flink】Flink 写入到 CSV BucketingSink 的使用方法
- Java native方法String转char*以及String[]转char**
- SAP License:更改MM物料基本计量单位
- tcp丢包率_网络编程 | TCP/IP基础知识
- (转)iOS 屏幕适配
- javascript 字符串中单引号和双引号区别
- 深度学习模型如何查看(hdfview + netron)
- 欧姆龙plc学习笔记(六)(从cx-one上传程序到欧姆龙plc)
- java高级软件工程师证书国家,看完这篇彻底明白了
- 数据分析面试——如何分析产品日活下降原因
- JScrollPane的使用
- R语言使用报错及处理总结(不断更新)
- 爱江山更爱美人服务器维修,微信爱江山更爱美人修改版-微信爱江山更爱美人VIP满级修改版预约 v1.0.0-友情手机站...
热门文章
- 程序员学习路线(个人)
- 图卷积(1)——从欧式空间到非欧式空间
- 5e显示非vac服务器,CSGO出现VAC无法验证的解决方法
- Node.js卸载与重装,zip与msi安装详解
- shell sftp 命令大全
- 怎么样把计算机桌面的图标改小,怎样将电脑桌面图标变小_三招搞定桌面图标太小问题-系统城...
- SQL 错误 [40000] [42000]: Error while compiling statement: FAILED
- 白盒测试哪种测试效果好_软件测试选择哪种测试方法比较好?
- 前端HTML和CSS面试题总结
- JDBC与ORM发展与联系 JDBC简介(九)