Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());

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?

like image 556
coderz Avatar asked Jan 08 '16 00:01

coderz


People also ask

What is the purpose of filter method of stream in Java 8?

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.

Does filter modify the original array Java?

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.

Can we convert stream to List in Java?

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.


1 Answers

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 new List. There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; if more control over the returned List is required, use toCollection(Supplier).

The original list remains unaffected.

like image 64
Mureinik Avatar answered Oct 02 '22 08:10

Mureinik