A mutable list is a list whose elements can be added, removed, or modified after the list has been created. It means, the content of the list can change over time.
Traditional approach of creating list from stream
We can convert a Java Stream to a list using the collect() method of the Stream interface and the Collectors.toList() method of the Collectors class
Code snippet
|
|
Output:
|
|
In above case we donot specify type of the list to be returned.
Also there is no guarantee of the mutability of the list returned.
But as per documentation, by using Collectors.toList()
“There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned”
Java stream to mutable list
In this case, the Collectors.toCollection() method is used to specify the type of collection to be used, which is an ArrayList of integers.
The toCollection() method takes a Supplier as an argument, which is used to create the collection. Here we are using a method reference ArrayList::new to create a new instance of an ArrayList.
The resulting list is mutable, which means you can modify it by adding or removing elements.
Here is the code example
|
|
Output:
|
|