Java 8 Streams: From List To Map

A list of POJOs:

public class Workshop {

    private String name;
    private int attendance;

    public Workshop(String name, int attendance) { = name;
        this.attendance = attendance;

    public String getName() {
        return name;

    public int getAttendance() {
        return attendance;

...can be directly converted into a Map using the built-in toMap Collector:

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static;
import static org.junit.Assert.assertThat;
import org.junit.Test;

public class CollectorsTest {

    public void listToMap() {
        List<Workshop> workshops
                = Arrays.asList(
                        new Workshop("bootstrap", 21),
                        new Workshop("effective", 42)
        Map<String, Integer> workshopsMap = workshops.
        assertThat(workshopsMap.size(), is(2));
        assertThat(workshopsMap.get("bootstrap"), is(21));
        assertThat(workshopsMap.get("effective"), is(42));



See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home:

NEW: Online Workhop Effective WebApps without Frameworks is also coming to: MUC Airport.

Airport MUC workshops: Web (SPA, PWAs, Offline, Desktop, Mobile) Applications Essentials and Effective Web Applications. No migrations. #usetheplatform

Podcast: and newsletter:

A book about rethinking Java EE Patterns


Hi Adam,

Your code is working only if the Name is unique for each Workshop in the Collection (Otherwise an Exception will be thrown that the map-key is not unique).
If Name is not unique, following code might help:

Map<String, Set<Workshop>> map =
.collect(Collectors.groupingBy(Workshop::getName, Collectors.mapping(Function.identity(), Collectors.toSet())));

Posted by Christian Thiel on January 29, 2016 at 08:47 AM CET #

The code will also throw an npe if the value is null, which is somewhat surprising for a Map. You are using int, so that is not happen in this case, but in other use cases with Object as a value it is possible.

Posted by Alex on January 30, 2016 at 07:02 AM CET #

Hi Adam,

I found this post very useful. Thank you!

I have a question, too:

Can we still convert easily if we had

private Person instructor;

and would like a Map of instructor names and attendance (assuming the field name exists in class Person)?

Posted by Cristina Fierbinteanu on October 14, 2016 at 12:07 PM CEST #

Nice Article

Posted by Yash on November 06, 2016 at 10:22 AM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments