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:
- We define a
Person
class to represent individuals withid
andname
properties. - We create a list of
Person
objects with unique IDs. - We use the
stream()
method to convert the list into a stream. - We use the
collect()
method withCollectors.toMap()
to collect the stream into aHashMap
. In this case:
Person::getId
is used as the key mapper, which extracts theid
from eachPerson
object.person -> person
is used as the value mapper, which keeps eachPerson
object as the value in theHashMap
.
- We print the resulting
HashMap
by iterating over its entries and displaying theid
andPerson
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.
- Difference between Anonymous Inner Class and Lambda Expression
- Java 8 Comparator comparing() example
- Java 8 Lambda Expressions Examples
- Write a program to find the nth Highest Salary using Java…
- Java 8 Functional Interface Examples
- Java 8 Supplier Examples
- Java 8 Consumer Examples
- Java 8 Predicate examples
- Java 8 default methods examples
- Java 8 Collection vs Stream
- Java 8 static methods examples
- Java 8 Method Reference Examples
- Java 8 Function interface Examples
- Java Stream filter() vs map()
- Java 8 Stream filter() examples