Cataclysm
Cataclysm

Reputation: 8568

Java8 : How to filter a map of List value via stream

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>.

Upvotes: 7

Views: 17759

Answers (1)

Zefick
Zefick

Reputation: 2119

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

Upvotes: 12

Related Questions