Java Stream to Mutable List

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package com.harishgowda84.jsondemo;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class App {

    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
        List<Integer> list = stream.collect(Collectors.toList());
        System.out.println(list);
        
    }


}

Output:

1
[1, 2, 3, 4, 5]

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package com.harishgowda84.jsondemo;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.ArrayList;


public class App {

    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
        List<Integer> list = stream.collect(Collectors.toCollection(ArrayList::new));
        System.out.println(list);

    }
}

Output:

1
[1, 2, 3, 4, 5]