Java8: how to filter a map of list values ​​through a stream

I'm still new to Java 8. I'm obsessed with filtering 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 fix the method doFilterbecause the error shows me cannot convert from List<List<Person>> to List<Person>.

+4
source share
1 answer

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());
}
+5
source

Source: https://habr.com/ru/post/1670261/


All Articles