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

时间:2017-02-20 05:48:47

标签: java java-8 java-stream

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

5

如何更正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

1 个答案:

答案 0 :(得分:8)

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

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