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?
The filter() function of the Java stream allows you to narrow down the stream's items based on a criterion. If you only want items that are even on your list, you can use the filter method to do this. This method accepts a predicate as an input and returns a list of elements that are the results of that predicate.
The filter() method creates a new array filled with elements that pass a test provided by a function. The filter() method does not execute the function for empty elements. The filter() method does not change the original array.
Stream class has toArray() method to convert Stream to Array, but there is no similar method to convert Stream to List or Set. Java has a design philosophy of providing conversion methods between new and old API classes e.g. when they introduced Path class in JDK 7, which is similar to java.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With