How to convert Stream to a Map in Java 8

Almost every developer has come into the following situation: You have a list of objects with IDs and you want to create a map to quickly access the right object with an ID.

As is so often the case, the Person class with ID, Firstname, and Lastname is used here:

public class Person 
    private String id;
    private String firstName;
    private String lastName;

    public Person(String id, String firstName, String lastName) { = id;
        this.firstName = firstName;
        this.lastName = lastName;
    ... Getter, Setter, toString, etc...
If you want to further process a list of objects, the Stream API is available from Java 8. To “collect” the elements of a stream into a collection, there is the collect() method. This method accepts a collector. The static utility class offer a selection of different standard collectors.

In the following example, a list of people is created first. In many cases such a list will probably come from a database.

List<Person> persons = new ArrayList<>();

persons.add(new Person("1", "Alex", "Itomir"));
persons.add(new Person("2", "Thomas", "Seintross"));
persons.add(new Person("3", "Emily", "Deggy"));

Map<String, Person> map = persons
        .collect(Collectors.toMap(p -> p.getId(), p -> p));



[2, Thomas, Seintross]

A stream can be created directly from the list and processed immediately with collect(). The factory method Collectors.toMap() has two arguments: a function that returns the key and a function for the corresponding value. In our case, we want the ID of the person as the key, which we get from the lambda expression p -> p.getId(). We want the person himself as the associated value, i.e. p -> p.

The result is a map which contains the IDs as keys and the corresponding objects as values.
java-mcq-multiple-choice-questions-and-answersJava MCQ – Multiple Choice Questions and Answers – OOPsThis collection of Java Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Java OOPs”.   1. Which of the…Read More

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *