strings.stream().map(s->map.put(s, s));
does nothing, since the stream pipeline is not processed until you complete the terminal operation. Therefore, the Map remains blank.
Adding a terminal operation to the stream pipeline will execute map.put(s, s) for each Stream element required by the terminal operation (for some terminal operations, only one element is required, while others require all Stream elements).
On the other hand, the second thread:
strings.stream().forEach(s->map.put(s, s));
ends with a terminal operation - forEach - that runs for each Stream element.
However, both fragments are used incorrectly by Stream s. To populate a Collection or Map based on the contents of the Stream , you must use collect() , which can create a Map or Collection and populate it as you like. forEach and Map have different goals.
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);
source share