Stream流的注意事项

1,toList()与collect(Collectors.toList())的区别

ArrayList<String> list = new ArrayList<>();
list.add("22");
String[] objects = new String[list.size()];
String[] array = list.toArray(objects);//List转数组
List<String> strings = list.stream().map(Object::toString).toList();
strings.add("aaa");//toList()返回的list不能修改

List<Integer> collect = list.stream().map(Integer::parseInt).collect(Collectors.toList());
collect.add(30);//collect(Collectors.toList());可以修改
for (Integer integer : collect) {
    System.out.println(integer);
}

2,Collectors.toMap流转换成map

Stream<Integer> stream = Stream.of(2, 2, 3, 4, 5, 6);
//第三个参数(a, b) -> a+b表示key发生冲突时value的合并方法
Map<Integer, String> collect = stream.collect(Collectors.toMap(Integer::valueOf, String::valueOf, (a, b) -> a+b, ConcurrentHashMap::new));
collect.forEach((a,b)->System.out.println(a+"  :"+b));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值