Collect Elements of a Stream into a Collection

suggest change

Collect with toList() and toSet()

Elements from a Stream can be easily collected into a container by using the Stream.collect operation:

System.out.println(Arrays
    .asList("apple", "banana", "pear", "kiwi", "orange")
    .stream()
    .filter(s -> s.contains("a"))
    .collect(Collectors.toList())
);
// prints: [apple, banana, pear, orange]

Other collection instances, such as a Set, can be made by using other Collectors built-in methods. For example, Collectors.toSet() collects the elements of a Stream into a Set.


Explicit control over the implementation of List or Set

According to documentation of Collectors#toList() and Collectors#toSet(), there are no guarantees on the type, mutability, serializability, or thread-safety of the List or Set returned.

For explicit control over the implementation to be returned, Collectors#toCollection(Supplier) can be used instead, where the given supplier returns a new and empty collection.

// strings is a Collection<String> declared earlier
// syntax with method reference
System.out.println(strings
        .stream()
        .filter(s -> s != null && s.length() <= 3)
        .collect(Collectors.toCollection(ArrayList::new))
);

// syntax with lambda
System.out.println(strings
        .stream()
        .filter(s -> s != null && s.length() <= 3)
        .collect(Collectors.toCollection(() -> new LinkedHashSet<>()))
);

Collecting Elements using toMap

The collector accumulates elements into a map whose key is the student id and whose value is the student name. Student is a class with getId() and getName(), declared elsewhere.

List<Student> students = new ArrayList<Student>();
students.add(new Student(1, "test1"));
students.add(new Student(2, "test2"));
students.add(new Student(3, "test3"));

Map<Integer, String> idToName = students.stream()
    .collect(Collectors.toMap(Student::getId, Student::getName));
System.out.println(idToName);

The map is a HashMap, so this order is not guaranteed:

{1=test1, 2=test2, 3=test3}

Collectors.toMap has another overload:

Collector<T, ?, Map<K, U>> toMap(Function<? super T, ? extends K> keyMapper,
        Function<? super T, ? extends U> valueMapper,
        BinaryOperator<U> mergeFunction)

The mergeFunction chooses the new value or keeps the old one when a key is repeated.

The merge function often looks like (s1, s2) -> s1, to keep the value already stored for a repeated key, or (s1, s2) -> s2, to replace it.

Collecting Elements to Map of Collections

Example: from ArrayList to Map<String, List<Subject>>

You often need to build a map of lists from a primary list. For example, from a list of students, build a map from each student to that student's subjects. The record syntax below requires Java 16 or later; the collector calls are the same with an ordinary class.

enum Subject { MATH, SCIENCE, GEOGRAPHY, ENGLISH, LITERATURE }
record Student(String name, Subject subject, double marks) {}

List<Student> list = new ArrayList<>();
list.add(new Student("Davis", Subject.MATH, 35.0));
list.add(new Student("Davis", Subject.SCIENCE, 12.9));
list.add(new Student("Davis", Subject.GEOGRAPHY, 37.0));

list.add(new Student("Sascha", Subject.ENGLISH, 85.0));
list.add(new Student("Sascha", Subject.MATH, 80.0));
list.add(new Student("Sascha", Subject.SCIENCE, 12.0));
list.add(new Student("Sascha", Subject.LITERATURE, 50.0));

list.add(new Student("Robert", Subject.LITERATURE, 12.0));

Map<String, List<Subject>> map = list.stream().collect(Collectors.groupingBy(
        Student::name,
        LinkedHashMap::new,
        Collectors.mapping(Student::subject, Collectors.toList())));
System.out.println(map);
{Davis=[MATH, SCIENCE, GEOGRAPHY], Sascha=[ENGLISH, MATH, SCIENCE, LITERATURE], Robert=[LITERATURE]}

Example: from ArrayList to Map<String, Map<Subject, List<Double>>>

enum Subject { MATH, SCIENCE, ENGLISH }
record Student(String name, Subject subject, int id, double marks) {}

List<Student> list = new ArrayList<>();
list.add(new Student("Davis", Subject.MATH, 1, 35.0));
list.add(new Student("Davis", Subject.SCIENCE, 2, 12.9));
list.add(new Student("Davis", Subject.MATH, 3, 37.0));
list.add(new Student("Davis", Subject.SCIENCE, 4, 37.0));

list.add(new Student("Sascha", Subject.ENGLISH, 5, 85.0));
list.add(new Student("Sascha", Subject.MATH, 1, 80.0));
list.add(new Student("Sascha", Subject.ENGLISH, 6, 12.0));
list.add(new Student("Sascha", Subject.MATH, 3, 50.0));

list.add(new Student("Robert", Subject.ENGLISH, 5, 12.0));

Map<String, Map<Subject, List<Double>>> map = list.stream().collect(Collectors.groupingBy(
        Student::name,
        LinkedHashMap::new,
        Collectors.groupingBy(
                Student::subject,
                LinkedHashMap::new,
                Collectors.mapping(Student::marks, Collectors.toList()))));

System.out.println(map);
{Davis={MATH=[35.0, 37.0], SCIENCE=[12.9, 37.0]}, Sascha={ENGLISH=[85.0, 12.0], MATH=[80.0, 50.0]}, Robert={ENGLISH=[12.0]}}

Cheat-Sheet

Goal Code
Collect to a List Collectors.toList()
Collect to an ArrayList with pre-allocated size Collectors.toCollection(() -> new ArrayList<>(size))
Collect to a Set Collectors.toSet()
Collect to a Set with better iteration performance Collectors.toCollection(() -> new LinkedHashSet<>())
Collect to a case-insensitive Set<String> Collectors.toCollection(() -> new TreeSet<>(String.CASE_INSENSITIVE_ORDER))
Collect to an EnumSet<AnEnum> (best performance for enums) Collectors.toCollection(() -> EnumSet.noneOf(AnEnum.class))
Collect to a Map<K,V> with unique keys Collectors.toMap(keyFunc, valFunc)
Map MyObject.getter() to a unique MyObject Collectors.toMap(MyObject::getter, Function.identity())
Map MyObject.getter() to multiple MyObjects Collectors.groupingBy(MyObject::getter)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents