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());
Original list is [3, 5, 4, 2, 5]. After "filter" and "collect" operation, the list changes to [3, 5, 4, 5].
Are all the operations perform on original list and does not create a new list? Or after "filter" and "collect" operation, return a new created list and ignore original list?
According to the Javadoc , passing the Collector
returned by Collectors.toList()
into the collect
method will create a new list.
public static <T> Collector<T,?,List<T>> toList()
Returns a
Collector
that accumulates the input elements into a newList
. There are no guarantees on the type, mutability, serializability, or thread-safety of theList
returned; if more control over the returnedList
is required, usetoCollection(Supplier)
.
The original list remains unaffected.
If you actually want to modify the original list, consider using removeIf
:
list.removeIf(i -> i < 2);
Stream operations are either intermediate or terminal. Intermediate operations return a stream so you can chain multiple intermediate operations. Terminal operations return void or something else.
Most of stream operations are non-interfering, it means that they don't modify the data source of the stream. But by calling the collect
method you are creating a new list and you're assigning it to list
Try this:
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);
Referring to Guava Lists.transform() function will help you understand why a new list needs to generate. Before JDK 7, Lists.transform() function is strongly recommended to implement similar feature.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.