Collectors类常用方法
文章目录
- Collectors类常用方法
-
- 1.toList、toSet、toMap
- 2.joining、counting、summingInt、minBy
- 3.groupingBy
1.toList、toSet、toMap
CollectorT, ?, ListT>> toList(); //收集为List集合
CollectorT, ?, SetT>> toSet(); //Set
CollectorT, ?, MapK,U>> toMap(Function? super T, ? extends K> keyMapper,Function? super T, ? extends U> valueMapper)//Map
//收集code为新List集合
ListString> strList = list.stream().map(DemoObj::getCode).collect(Collectors.toList());
//收集code为新Set集合
SetString> collect = list.stream().map(DemoObj::getCode).collect(Collectors.toSet());
//将code为key,amount为值作为map集合
MapString, Integer> collect = list.stream().collect(Collectors.toMap(DemoObj::getCode, DemoObj::getAmount));
2.joining、counting、summingInt、minBy
//指定字符拼接
CollectorCharSequence, ?, String> joining(CharSequence delimiter);
//统计 等同于Stream的count()
T> CollectorT, ?, Long> counting();
//求和,等同于Stream的mapToInt(ToIntFunction super 服务器托管T> mapper).服务器托管sum()
T> CollectorT, ?, Integer> summingInt(ToIntFunction? super T> mapper)
//获取最小值,等同于Stream的min(Comparator super T> comparator)
T> CollectorT, ?, OptionalT>> minBy(Comparator? super T> comparator)
//遍历list集合取将DemoObj对象的code属性用逗号拼接
String str = list.stream().map(DemoObj::getCode).collect(Collectors.joining(","));
Long collect = list.stream().map(DemoObj::getCode).collect(Collectors.counting());
//求和,等同于mapToInt(DemoObj::getAmount).sum()
Integer collect = list.stream().collect(Collectors.summingInt(DemoObj::getAmount));
//获取最小金额,等同于 min(Comparator.comparingInt(DemoObj::getAmount))
OptionalDemoObj> collect = list.stream().collect(Collectors.minBy(Comparator.comparingInt(DemoObj::getAmount)));
3.groupingBy
T, K> CollectorT, ?, MapK, ListT>>> groupingBy(Function? super T, ? extends K> classifier);//分组
MapInteger, ListDemoObj>> collect = list.stream().collect(Collectors.groupingBy(DemoObj::getAmount));//按金额分组
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
相关推荐: 深入JVM核心:Java虚拟机原理解析与性能调优实战
JVM(Java虚拟机)原理: JVM是Java程序运行的虚拟机环境,它为Java程序提供了一个独立于硬件和操作系统的运行时环境。JVM的主要组成部分包括: 类加载器(ClassLoader): 负责加载Java类文件到内存中,包括验证、准备、解析、加载和初始…