I know map is not a terminal operation, but could someone explain this in more detail?
userList.stream().map(i -> {
System.out.println(i);
return i;
}).collect(Collectors.toList());
List<User> arrayList = new ArrayList<>();
userList.stream().forEach(i -> {
System.out.println(i);
arrayList.add(i);
});
Since map
is not a terminal operation, it will be executed only when the terminal operation collect
is executed.
So we should compare the two terminal operations of the two snippets - collect
vs. forEach
.
collect(Collectors.toList())
creates a List
instance and adds all the elements of the Stream
to it, after applying the Function
passed to map
on each of them. Applying the map Function
prints each element in your case, and returns the element unchanged.
forEach
applies the Consumer
pass to it to it element of the Stream
, so in your case it prints each element and adds it to the ArrayList
you created prior to the stream pipeline.
Both snippets produce the same output, but in different ways. Note that Collectors.toList()
currently produce an ArrayList
, but it gives no guarantee regarding the type of List
returned, so that may change in the future.