adam bien's blog

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) {
        this.name = 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 java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;

public class CollectorsTest {

    @Test
    public void listToMap() {
        List<Workshop> workshops
                = Arrays.asList(
                        new Workshop("bootstrap", 21),
                        new Workshop("effective", 42)
                );
        
        Map<String, Integer> workshopsMap = workshops.
                stream().
                collect(Collectors.toMap(Workshop::getName,Workshop::getAttendance));
      
        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: airhacks.io.