I'm still a beginner of Java 8. I'm getting stuck on filtering a Map of List values. Here is my code
public class MapFilterList {
private static Map<String, List<Person>> personMap = new HashMap<>();
public static void main(String[] args) {
Person p1 = new Person("John", 22);
Person p2 = new Person("Smith", 45);
Person p3 = new Person("Sarah", 27);
List<Person> group1 = new ArrayList<>();
group1.add(p1);
group1.add(p2);
List<Person> group2 = new ArrayList<>();
group2.add(p2);
group2.add(p3);
List<Person> group3 = new ArrayList<>();
group3.add(p3);
group3.add(p1);
personMap.put("group1", group1);
personMap.put("group2", group2);
personMap.put("group3", group3);
doFilter("group1").forEach(person -> {
System.out.println(person.getName() + " -- " + person.getAge());
});
}
public static List<Person> doFilter(String groupName) {
return personMap.entrySet().stream().filter(key -> key.equals(groupName)).map(map -> map.getValue()).collect(Collectors.toList());
}
}
How can I make to correct doFilter
method because the error show me cannot convert from List<List<Person>> to List<Person>
.
Filter Map Elements using Java Streams Firstly, we created a stream of our Map#Entry instances and used filter() to select only the Entries where person name starts with 'J'. Lastly, we used Collectors#toMap() to collect the filtered entry elements in the form of a new Map.
We can filter a Map in Java 8 by converting the map. entrySet() into Stream and followed by filter() method and then finally collect it using collect() method.
If I understood correctly you need the following code:
public static List<Person> doFilter(String groupName) {
return personMap.entrySet().stream()
.filter(entry -> entry.getKey().equals(groupName))
.map(entry -> entry.getValue())
.flatMap(List::stream)
// as an option to replace the previous two
// .flatMap(entry -> entry.getValue().stream())
.collect(Collectors.toList());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With