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?