Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 817
Cataclysm Avatar asked Feb 20 '17 05:02

Cataclysm


People also ask

How do I filter a map with a stream?

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.

How do I filter a map based on values in Java 8?

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.


1 Answers

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());
}
like image 151
Zefick Avatar answered Sep 24 '22 20:09

Zefick