繁体   English   中英

Java8:如何通过流过滤List值的映射

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

我仍然是Java 8的初学者。我正在坚持过滤List of List值。 这是我的代码

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

如何更正doFilter方法因为错误显示我cannot convert from List<List<Person>> to List<Person>

如果我理解正确,您需要以下代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM