Java 8 example to Collect stream into a HashMap with Lambda

In Java 8, you can collect elements from a stream into a HashMap using the Collectors.toMap() method with lambda expressions. Below is a complete Java example that demonstrates how to collect elements from a stream into a HashMap using lambda expressions.

import java.util.*;
import java.util.stream.Collectors;

public class StreamToHashMapExample {
    public static void main(String[] args) {
        // Create a list of persons with unique IDs
        List<Person> persons = Arrays.asList(
            new Person(1, "Alice"),
            new Person(2, "Bob"),
            new Person(3, "Charlie"),
            new Person(4, "David")
        );

        // Collect the list of persons into a HashMap with ID as the key
        Map<Integer, Person> personMap = persons.stream()
            .collect(Collectors.toMap(Person::getId, person -> person));

        // Print the resulting HashMap
        for (Map.Entry<Integer, Person> entry : personMap.entrySet()) {
            System.out.println("ID: " + entry.getKey() + ", Person: " + entry.getValue());
        }
    }

    static class Person {
        private int id;
        private String name;

        public Person(int id, String name) {
            this.id = id;
            this.name = name;
        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return "Person{id=" + id + ", name='" + name + "'}";
        }
    }
}

Explanation:

  1. We define a Person class to represent individuals with id and name properties.
  2. We create a list of Person objects with unique IDs.
  3. We use the stream() method to convert the list into a stream.
  4. We use the collect() method with Collectors.toMap() to collect the stream into a HashMap. In this case:
  • Person::getId is used as the key mapper, which extracts the id from each Person object.
  • person -> person is used as the value mapper, which keeps each Person object as the value in the HashMap.
  1. We print the resulting HashMap by iterating over its entries and displaying the id and Person for each entry.

Expected Output:

ID: 1, Person: Person{id=1, name='Alice'}
ID: 2, Person: Person{id=2, name='Bob'}
ID: 3, Person: Person{id=3, name='Charlie'}
ID: 4, Person: Person{id=4, name='David'}

In this example, we’ve collected the list of Person objects into a HashMap using Java 8 Streams and lambda expressions, where the id is used as the key in the HashMap, and the Person object itself is used as the value.

That’s all about the Java 8 example to Collect stream into a HashMap with Lambda.

Other Java 8 tutorials.