strings.stream().map(s->map.put(s, s));
什么都不做,因为在执行终端操作之前不会处理流管道。因此,
Map残留物为空。
在流管道中添加终端操作将导致
map.put(s,s)针对
Stream终端操作所需的每个元素执行操作(某些终端操作仅需要一个元素,而其他终端操作则需要的所有元素
Stream)。
另一方面,第二个流管道:
strings.stream().forEach(s->map.put(s, s));
以终端操作-结束,该操作
forEach对的每个元素执行
Stream。
也就是说,两个摘要都滥用
Streams。为了根据的内容填充a
Collection或a ,您应该使用,可以创建a 或a
并根据需要填充它。并有不同的目的。
Map``Stream``collect()``Map``Collection``forEach``map
例如,创建一个
Map:
List<String> strings = Lists.newArrayList("1", "2");Map<String, String> map = strings.stream().collect(Collectors.toMap(Function.identity(), Function.identity()));System.out.println(map);


