java8流图在这里做了什么? [英] what does java8 stream map do here?
问题描述
我对java8流中 map()
和 forEach()
方法之间的区别感到困惑。例如,
I was confused about the difference between map()
and forEach()
method in java8 stream. For instance,
List<String> strings = Lists.newArrayList("1", "2");
Map<String, String> map = Maps.newHashMap();
strings.stream().map(s->map.put(s, s));
System.out.println(map);
我在这里得到空输出,但如果我将地图更改为 forEach()
就像
I got empty output here, but if I change map to forEach()
just like
List<String> strings = Lists.newArrayList("1", "2");
Map<String, String> map = Maps.newHashMap();
strings.stream().forEach(s->map.put(s, s));
System.out.println(map);
我可以
{1 = 1,2 = 2}
{1=1, 2=2}
为什么它只是没有运行 map ()
方法?它们之间有什么区别?
Why it just didn't run map()
method? What's difference between them?
推荐答案
strings.stream().map(s->map.put(s, s));
什么都不做,因为在执行终端操作之前不会处理流管道。因此地图
仍为空。
does nothing, since the stream pipeline is not processed until you execute a terminal operation. Therefore the Map
remains empty.
向流管道添加终端操作将导致执行 map.put(s,s)
终端操作所需的 Stream
的每个元素(某些终端操作只需要一个元素,而其他元素则需要 Stream $ c的所有元素$ c>)。
Adding a terminal operation to the stream pipeline will cause map.put(s, s)
to be executed for each element of the Stream
required by the terminal operation (some terminal operations require just one element, while others require all elements of the Stream
).
另一方面,第二个流管道:
On the other hand, the second stream pipeline:
strings.stream().forEach(s->map.put(s, s));
以终端操作结束 - forEach
- 这是为 Stream
的每个元素执行的。
ends with a terminal operation - forEach
- which is executed for each element of the Stream
.
这就是说,两个片段都在滥用流
秒。为了根据 Stream的内容填充
Collection
或 Map
code>,您应该使用 collect()
,这可以创建地图
或收集
并按照您的喜好填充它。 forEach
和 map
有不同的用途。
That said, both snippets are misusing Stream
s. In order to populate a Collection
or a Map
based on the contents of the Stream
, you should use collect()
, which can create a Map
or a Collection
and populate it however you like. forEach
and map
have different purposes.
例如,创建地图
:
List<String> strings = Lists.newArrayList("1", "2");
Map<String, String> map = strings.stream()
.collect(Collectors.toMap(Function.identity(),
Function.identity()));
System.out.println(map);
这篇关于java8流图在这里做了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!