We can convert list of POJO to Map in Java 8 with the help of the Stream API’s method, with concise code. In this topic, we will convert list of POJO to Map step-by-step.
Steps to convert List of POJO to Map Java 8
1. Define Your POJO Class
public class User {
private Long id;
private String name;
public User() {}
public User(Long id, String name) {
this.id = id;
this.name = name;
}
// Getters
public Long getId() { return id; }
public String getName() { return name; }
// toString for display
@Override
public String toString() {
return "User{id=" + id + ", name='" + name + "'}";
}
}
2. Convert List of POJOs to Map Using Java 8
import java.util.*;
import java.util.stream.Collectors;
public class ConvertListToMap {
public static void main(String[] args) {
List<User> users = Arrays.asList(
new User(1L, "Alice"),
new User(2L, "Bob"),
new User(3L, "Charlie")
);
// Convert List<User> to Map<Long, User>
Map<Long, User> userMap = users.stream()
.collect(Collectors.toMap(User::getId, user -> user));
// Print the result
userMap.forEach((id, user) -> System.out.println(id + " => " + user));
}
}
Output
1 => User{id=1, name='Alice'}
2 => User{id=2, name='Bob'}
3 => User{id=3, name='Charlie'}
Advanced Variants
Convert to Map<Id, Name>
Map<Long, String> nameMap = users.stream().collect(Collectors.toMap(User::getId, User::getName));
Handle Duplicate Keys (with Merge Function)
Map<Long, User> safeMap = users.stream()
.collect(Collectors.toMap(
User::getId,
user -> user,
(existing, replacement) -> existing // or use replacement
));
Conclusion
In this topic, we learnt how to convert list of POJO to Map using the Stream API’s method[Collectors.toMap()].