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);
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);
I can get
{1=1, 2=2}
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.
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));
ends with a terminal operation - forEach
- which is executed for each element of the Stream
.
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.
For example, to create a 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);