stream().map().collect()用法
List users = getList(); //从数据库查询的用户集合
获取User的身份证号码
用for循环
for(int i=0;i<users.size();i++){
idcards.add(users.get(i).getIdcard());
}
使用stream
List idcards= users.stream().map(User::getIdcard).collect(Collectors.toList())
Collectors.joining 收集器 支持灵活的参数配置,可以指定字符串连接时的 分隔符,前缀 和 后缀 字符串
// 定义人名数组
final String[] names = {“Zebe”, “Hebe”, “Mary”, “July”, “David”};
Stream stream1 = Stream.of(names);
Stream stream2 = Stream.of(names);
Stream stream3 = Stream.of(names);
// 拼接成 [x, y, z] 形式
String result1 = stream1.collect(Collectors.joining(", “, “[”, “]”));
// 拼接成 x | y | z 形式
String result2 = stream2.collect(Collectors.joining(” | “, “”, “”));
// 拼接成 x -> y -> z] 形式
String result3 = stream3.collect(Collectors.joining(” -> ", “”, “”))
其他用法
示例:List
总结: 预定义收集器可以用groupby对流中元素进行分组或者用partitioningBy进行分区
收集器可以高效的复合起来,进行多级分组,多级分区和归约
可以自己实现collector接口进行定义自己的收集器