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));

猜你喜欢

转载自blog.csdn.net/lc257/article/details/127742582
今日推荐