what does java8 stream map do here?

Viewed 2301

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?

4 Answers

The documentation for each instance method of Stream states whether the method is an intermediate operation, or a terminal operation. Only terminal operations will cause the stream to be evaluated. Intermediate operations may not be performed unless required by a downstream terminal operation.

This can improve efficiency, especially when the terminal operation is a short-circuit operation, like findAny(). A pipeline with a complex set of intermediate operations doesn't need to be executed for additional elements after a matching element has been found.

In your case, forEach() is a terminal operation; it causes the pipeline to be executed. map() is an intermediate operation; it doesn't have to do anything unless required by a downstream terminal operation.

Related