Will Java 8 create a new list after using Stream "filter" and "collect"?
I have code using Java8:
List<Integer> list = new ArrayList<Integer>(); list.add(3); list.add(5); list.add(4); list.add(2); list.add(5); list = list.stream().filter(i -> i >= 3).collect(Collectors.toList()); The initial list is [3, 5, 4, 2, 5]. After the operation "filter" and "collection" the list changes to [3, 5, 4, 5].
Are all operations in the source list performed and a new list is not created? Or after the operation "filter" and "collect", return the newly created list and ignore the original list?
Calling collect with Collectors.toList() will create a new list. The source list is not streamed.
If you really want to change the original list, consider using removeIf :
list.removeIf(i -> i < 2); Flow operations are intermediate or final. Intermediate operations return a stream, so you can bind several intermediate operations. Terminal operations return a void or something else.
Most stream operations do not interfere, which means that they do not change the stream data source. But by calling the collect method, you create a new list and assign it to list
Try the following:
List<Integer> list = new ArrayList<Integer>(); list.add(3); list.add(5); list.add(4); list.add(2); list.add(5); List<Integer> list2 = list.stream().filter(i -> i >= 3).collect(Collectors.toList()); System.out.println("list: "+list); System.out.println("list2: "+list2); By referring to the Guava Lists.transform () function, you can understand why you need to generate a new list. Before JDK 7, the List.transform () function is strongly recommended to implement a similar function.