首页 > 解决方案 > Java 8 让所有地址以 P 开头的员工

问题描述

我有如下员工和地址类

class Employee {
    private String name;
    private int age;
    private List<Address> addresses;
    //getter and setter
}

class Address {
    private String city;
    private String state;
    private String country;
    //getter and setter
}

使用 java 8 过滤器我想打印所有以 P 开头的城市的员工

在下面的代码中添加什么来获取该过滤地址的 emp

employees.stream()
    .map(Employee::getAddresses)
    .flatMap(Collection::stream)
    .filter(children -> children.getCity().startsWith("p"))
    .collect(Collectors.toList())
    .forEach(System.out::println);

提前致谢。

标签: javafilterjava-8java-stream

解决方案


使用anyMatchinfilter而不是mapping :

employees.stream()
         .filter(employee -> employee.getAddresses().stream()
                 .anyMatch(adr -> adr.getCity().startsWith("p")))
         .forEach(System.out::println); // collecting not required to use forEach

推荐阅读