list = new ArrayList(); ...">

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?

+7
java list java-8 java-stream
source share
5 answers

Calling collect with Collectors.toList() will create a new list. The source list is not streamed.

+16
source share

If you really want to change the original list, consider using removeIf :

 list.removeIf(i -> i < 2); 
+10
source share

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

+3
source share

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); 
+1
source share

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.

+1
source share

All Articles