

This article contains Java 8 Convert Map to List using Stream Example like Map to Value List, Map to key List, Map filter based on key, Map filter based on value using java 8 filter.
Table of Contents
Example 1: Map Value to List using stream
HashMap<Integer, Employee> employeeHashMap = new HashMap();
employeeHashMap.put(1, new Employee(1, "Jone"));
employeeHashMap.put(2, new Employee(2, "Shone"));
java.util.List<Employee> employeeList = employeeHashMap.entrySet()
.stream()
.map(java.util.Map.Entry::getValue) // map too value
.collect(Collectors
.toList()); // collect value list
employeeList.forEach(employee -> {
System.out.println(employee.getName());
});Output:
Jone Shone
Example 2: Map key to List using stream
HashMap<Integer, Employee> employeeHashMap = new HashMap();
employeeHashMap.put(1, new Employee(1, "Jone"));
employeeHashMap.put(2, new Employee(2, "Shone"));
java.util.List<Integer> emplyeeMapKey = employeeHashMap.entrySet()
.stream()
.mapToInt(java.util.Map.Entry::getKey) // using map get only key
.collect(ArrayList::new, ArrayList::add, ArrayList::addAll); // convert Integer Stream to List
emplyeeMapKey.forEach(employeeId -> {
System.out.println(employeeId);
});Output:
1 2
Example 3: Map Key to List with filter
HashMap<Integer, Employee> employeeHashMap = new HashMap();
employeeHashMap.put(1, new Employee(1, "Jone"));
employeeHashMap.put(2, new Employee(2, "Shone"));
employeeHashMap.put(3, new Employee(3, "Chapli"));
employeeHashMap.put(4, new Employee(4, "Bost"));
employeeHashMap.put(5, new Employee(5, "Novo"));
java.util.Map<Integer, Employee> filterResultMap = employeeHashMap.entrySet()
.stream()
.filter((entry -> {
return entry.getKey() > 3; // it will filter based on key
}))
.collect(Collectors // create map with filtered data
.toMap(k -> k.getKey(), v -> v
.getValue()));
filterResultMap.forEach((k, v) -> {
System.out.println(k + " " + v.getName());
});Output:
4 Bost 5 Novo
Example 4 : Map values to List using filter
HashMap<Integer, Employee> employeeHashMap = new HashMap();
employeeHashMap.put(1, new Employee(1, "Jone"));
employeeHashMap.put(2, new Employee(2, "Shone"));
employeeHashMap.put(3, new Employee(3, "Chapli"));
employeeHashMap.put(4, new Employee(4, "Bost"));
employeeHashMap.put(5, new Employee(5, "Novo"));
java.util.Map<Integer, Employee> filterResultMap = employeeHashMap.entrySet()
.stream()
.filter((entry -> {
return entry.getValue().getName().endsWith("e"); // it will filter based on map value
}))
.collect(Collectors
.toMap(k -> k.getKey(), v -> v // create map with filtered data
.getValue()));
filterResultMap.forEach((k, v) -> {
System.out.println(k + " " + v.getName());
});Output:
1 Jone 2 Shone
References:
Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.
