Stream collect Collectors 常用详细实例
返回List集合: toList()
用于将元素累积到List集合中。它将创建一个新List集合(不会更改当前集合)。
List<Integer> integers = Arrays.asList(1,2,3,4,5,6,6);
integers.stream().map(x -> x*x).collect(Collectors.toList());
返回Set集合: toSet()
用于将元素累积到Set集合中。它会删除重复元素。
List<Integer> integers = Arrays.asList(1,2,3,4,5,6,6);
integers.stream().map(x -> x*x).collect(Collectors.toSet());
返回指定的集合: toCollection()
可以将元素累积到指定的集合中。
List<Integer> integers = Arrays.asList(1,2,3,4,5,6,6);
integers
.stream()
.filter(x -> x >2)
.collect(Collectors.toCollection(LinkedList::new));// output: [3,4,5,6,6]
计算元素数量: Counting()
用于返回计算集合中存在的元素个数。
List<Integer> integers = Arrays.asList(1,2,3,4,5,6,6);
Long collect = integers
.stream()
.filter(x -> x <4)
.collect(Collectors.counting());// output: 3
求最小值: minBy()
用于返回列表中存在的最小值。
List<Integer> integers = Arrays.asList(1,2,3,4,5,6,6);
List<String> strings = Arrays.asList("alpha","beta","gamma");
integers
.stream()
.collect(Collectors.minBy(Comparator.naturalOrder()))
.get();// output: 1
strings
.stream()
.collect(Collectors.minBy(Comparator.naturalOrder()))
.get();// output: alpha
按照整数排序返回1,按照字符串排序返回alpha
可以使用reverseOrder()方法反转顺序。
List<Integer> integers = Arrays.asList(1,2,3,4,5,6,6);
List<String> strings = Arrays.asList("alpha","beta","gamma");
integers
.stream()
.collect(Collectors.minBy(Comparator.reverseOrder()))
.get();// output: 6 strings
.stream()
.collect(Collectors.minBy(Comparator.reverseOrder()))
.get();// output: gamma
同时可以自定义的对象定制比较器。
求最大值: maxBy()
和最小值方法类似,使用maxBy()方法来获得最大值。
List<String> strings = Arrays.asList("alpha","beta","gamma");
strings
.stream()
.collect(Collectors.maxBy(Comparator.naturalOrder()))
.get();// output: gamma
分区列表:partitioningBy()
用于将一个集合划分为2个集合并将其添加到映射中,1个满足给定条件,另一个不满足,例如从集合中分离奇数。因此它将在map中生成2条数据,1个以true为key,奇数为值,第2个以false为key,以偶数为值。
List<String> strings = Arrays.asList("a","alpha","beta","gamma");
Map<Boolean, List<String>> collect1 = strings
.stream()
.collect(Collectors.partitioningBy(x -> x.length() > 2));// output: {false=[a], true=[alpha, beta, gamma]}
这里我们将长度大于2的字符串与其余字符串分开。
返回不可修改的List集合:toUnmodifiableList()
用于创建只读List集合。任何试图对此不可修改List集合进行更改的尝试都将导致UnsupportedOperationException。
List<String> strings = Arrays.asList("alpha","beta","gamma");
List<String> collect2 = strings
.stream()
.collect(Collectors.toUnmodifiableList());// output: ["alpha","beta","gamma"]
返回不可修改的Set集合:toUnmodifiableSet()
用于创建只读Set集合。任何试图对此不可修改Set集合进行更改的尝试都将导致UnsupportedOperationException。它会删除重复元素。
List<String> strings = Arrays.asList("alpha","beta","gamma","alpha");
Set<String> readOnlySet = strings
.stream()
.sorted()
.collect(Collectors.toUnmodifiableSet());// output: ["alpha","beta","gamma"]
连接元素:Joining()
用指定的字符串链接集合内的元素。
List<String> strings = Arrays.asList("alpha","beta","gamma");
String collect3 = strings
.stream()
.distinct()
.collect(Collectors.joining(","));// output: alpha,beta,gammaString collect4 = strings
.stream()
.map(s -> s.toString())
.collect(Collectors.joining(",","[","]"));// output: [alpha,beta,gamma]
Long类型集合的平均值:averagingLong()
查找Long类型集合的平均值。
注意:返回的是Double类型而不是 Long类型
List<Long> longValues = Arrays.asList(100l,200l,300l);
Double d1 = longValues
.stream()
.collect(Collectors.averagingLong(x -> x * 2));// output: 400.0
Integer类型集合的平均值:averagingInt()
查找Integer类型集合的平均值。
注意:返回的是Double类型而不是 int类型
List<Integer> integers = Arrays.asList(1,2,3,4,5,6,6);
Double d2 = integers
.stream()
.collect(Collectors.averagingInt(x -> x*2));// output: 7.714285714285714
Double类型集合的平均值:averagingDouble()
查找Double类型集合的平均值。
List<Double> doubles = Arrays.asList(1.1,2.0,3.0,4.0,5.0,5.0);
Double d3 = doubles
.stream()
.collect(Collectors.averagingDouble(x -> x));// output: 3.35
创建Map:toMap()
根据集合的值创建Map。
List<String> strings = Arrays.asList("alpha","beta","gamma");
Map<String,Integer> map = strings
.stream()
.collect(Collectors
.toMap(Function.identity(),String::length));// output: {alpha=5, beta=4, gamma=5}
创建了一个Map,其中集合值作为key,在集合中的出现次数作为值。
在创建map时处理列表的重复项
集合中可以包含重复的值,因此,如果想从列表中创建一个Map,并希望使用集合值作为map的key,那么需要解析重复的key。由于map只包含唯一的key,可以使用比较器来实现这一点。
List<String> strings = Arrays.asList("alpha","beta","gamma","beta");
Map<String,Integer> map = strings
.stream()
.collect(Collectors
.toMap(Function.identity(),String::length,(i1,i2) -> i1));// output: {alpha=5, gamma=5, beta=4}
Function.identity()指向集合中的值,i1和i2是重复键的值。可以只保留一个值,这里选择i1,也可以用这两个值来计算任何东西,比如把它们相加,比较和选择较大的那个,等等。
整数求和:summingInt ()
查找集合中所有整数的和。它并不总是初始集合的和,就像我们在下面的例子中使用的我们使用的是字符串列表,首先我们把每个字符串转换成一个等于它的长度的整数,然后把所有的长度相加。
List<String> strings = Arrays.asList("alpha","beta","gamma");
Integer collect4 = strings
.stream()
.collect(Collectors.summingInt(String::length));// output: 18
或直接集合值和
List<Integer> integers = Arrays.asList(1,2,3,4,5,6,6);
Integer sum = integers
.stream()
.collect(Collectors.summingInt(x -> x));// output: 27
double求和:summingDouble ()
类似于整数求和,只是它用于双精度值
List<Double> doubleValues = Arrays.asList(1.1,2.0,3.0,4.0,5.0,5.0);
Double sum = doubleValues
.stream()
.collect(Collectors.summingDouble(x ->x));// output: 20.1
Long求和:summingLong ()
与前两个相同,用于添加long值或int值。可以对int值使用summinglong(),但不能对long值使用summingInt()。
List<Long> longValues = Arrays.asList(100l,200l,300l);
Long sum = longValues
.stream()
.collect(Collectors.summingLong(x ->x));// output: 600
汇总整数:summarizingInt ()
它给出集合中出现的值的所有主要算术运算值,如所有值的平均值、最小值、最大值、所有值的计数和总和。
List<Integer> integers = Arrays.asList(1,2,3,4,5,6,6);
IntSummaryStatistics stats = integers
.stream()
.collect(Collectors.summarizingInt(x -> x ));//output: IntSummaryStatistics{count=7, sum=27, min=1, average=3.857143, max=6}
可以使用get方法提取不同的值,如:
stats.getAverage();
// 3.857143stats.getMax();
// 6stats.getMin();
// 1stats.getCount();
// 7stats.getSum();
// 27
分组函数:GroupingBy ()
GroupingBy()是一种高级方法,用于从任何其他集合创建Map。
List<String> strings = Arrays.asList("alpha","beta","gamma");
Map<Integer, List<String>> collect = strings
.stream()
.collect(Collectors.groupingBy(String::length));// output: {4=[beta, beta], 5=[alpha, gamma]}
它将字符串长度作为key,并将该长度的字符串列表作为value。
List<String> strings = Arrays.asList("alpha","beta","gamma");
Map<Integer, LinkedList<String>> collect1 = strings
.stream()
.collect(Collectors.groupingBy(String::length,
Collectors.toCollection(LinkedList::new)));// output: {4=[beta, beta], 5=[alpha, gamma]}
这里指定了Map中需要的列表类型(Libkedlist)。
Stream collect Collectors 常用详细实例的更多相关文章
- Java--java.util.stream.Collectors文档实例
// java.util.stream.Collectors 类的主要作用就是辅助进行各类有用的 reduction 操作,例如转变输出为 Collection,把 Stream 元素进行归组. pu ...
- Java8 Stream流API常用操作
Java版本现在已经发布到JDK13了,目前公司还是用的JDK8,还是有必要了解一些JDK8的新特性的,例如优雅判空的Optional类,操作集合的Stream流,函数式编程等等;这里就按操作例举一些 ...
- 【JDK8】Java8 Stream流API常用操作
Java版本现在已经发布到JDK13了,目前公司还是用的JDK8,还是有必要了解一些JDK8的新特性的,例如优雅判空的Optional类,操作集合的Stream流,函数式编程等等;这里就按操作例举一些 ...
- java stream中Collectors的用法
目录 简介 Collectors.toList() Collectors.toSet() Collectors.toCollection() Collectors.toMap() Collectors ...
- 【Java 8】 集合间转换工具——Stream.collect
集合运算 交集 (list1 + list2) List<T> intersect = list1.stream() .filter(list2::contains) .collect(C ...
- java 数据类型:Stream流 对象转换为集合collect(Collectors.toList()) ;常用方法count,limit,skip,concat,max,min
集合对象.stream() 获取流对象,对元素批处理(不改变原集合) 集合元素循环除了用for循环取出,还有更优雅的方式.forEach 示例List集合获取Stream对象进行元素批处理 impor ...
- windows phone 8.1常用启动器实例
---恢复内容开始--- 小梦今天给大家分享一下windows phone 8.1常用启动器实例,包括: 电话启动器 短信启动器 邮件启动器 添加约会|备忘到日历 地图启动器 地图路线启动器 wind ...
- 轻量级HTTP服务器Nginx(常用配置实例)
轻量级HTTP服务器Nginx(常用配置实例) 文章来源于南非蚂蚁 Nginx作为一个HTTP服务器,在功能实现方面和性能方面都表现得非常卓越,完全可以与Apache相媲美,几乎可以实现Apa ...
- 【转贴】Windows常用命令实例
Windows常用命令实例 https://www.cnblogs.com/linyfeng/p/6261629.html 熟练使用DOS常用命令有助于提高工作效率. 1.windows+R:打开运行 ...
随机推荐
- SpringBoot教程(学习资源)
SpringBoot教程 SpringBoot–从零开始学SpringBoot SpringBoot教程1 SpringBoot教程2 --SpringBoot教程2的GitHub地址 SpringB ...
- 某企业桌面虚拟化项目-Citrix虚拟桌面解决方案
xxx桌面虚拟化项目Citrix解决方案 xxx桌面虚拟化项目 Citrix解决方案 1 项目背景 秉承"尊重个性.创造价值.贡献于社会"的企业理念和开拓创新的精神,xxx所制造. ...
- building sasl.wrapper extention
yum install gcc-c++ python-devel.x86_64 cyrus-sasl-devel.x86_64 pip install pyhs2 ref: https://www.o ...
- Android Thermal HAL 降龙十八掌
基本概念 参阅下面两篇文章,就可以大概了解一些概念的内容了 https://source.android.com/devices/architecture/hidl/thermal-mitigatio ...
- Python知识整理(二)
6.高级特性--简化代码量 1.切片 L[0:3]表示,从索引0开始取,直到索引3为止,但不包括索引3.即索引0,1,2,正好是3个元素. 如果第一个索引是0,还可以省略:L[:3] Python支持 ...
- React-Router示例(重定向与withRouter)
1.withRouter作用:把不是通过路由切换过来的组件中,将react-router 的 history.location.match 三个对象传入props对象上 默认情况下必须是经过路由匹 ...
- IDEA Plugin,写一个看股票指数和K线的插件
作者:小傅哥 博客:https://bugstack.cn 沉淀.分享.成长,让自己和他人都能有所收获! 一.前言 没招了,不写点刺激的,你总是不好好看! 以前,我不懂.写的技术就是技术内容,写的场景 ...
- 字符编码和python文件操作
字符编码和文件操作 目录 字符编码和文件操作 1. 字符编码 1.1 什么是字符编码 1.2 字符编码的发展史 1.2.1 ASCII码 1.2.2 各国编码 1.2.3 Unicode 1.3 字符 ...
- python实现图像梯度
一,定义与作用 图像梯度作用:获取图像边缘信息 二,Sobel 算子与函数的使用 (1)Sobel 算子------来计算变化率 (2)Sobel函数的使用 (3-1)代码实现(分别): (3-2)代 ...
- [loj2469]最小方差生成树
2018年论文题 约定:令点集$V=[1,n]$.边集$E=[1,m]$,记$m$条边依次为$e_{i}=(x_{i},y_{i},c_{i})$(其中$1\le i\le m$),将其按照$c_{i ...