java - 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);
提前致谢。
解决方案
使用anyMatch
infilter
而不是map
ping :
employees.stream()
.filter(employee -> employee.getAddresses().stream()
.anyMatch(adr -> adr.getCity().startsWith("p")))
.forEach(System.out::println); // collecting not required to use forEach
推荐阅读
- ios - 铸造一个泛型类
- swagger - 如何在 Loopback 4 的 Swagger 中添加“授权标头”输入?
- javascript - Javascript 按日期过滤 JSON
- java - 为什么 Spring 强调紧密耦合,尽管它可以通过编程方式克服?
- r - R:R中的“折叠”行
- python-3.x - python derived class constructor
- azure - Azure Application Insight:将遥测流式传输到文件
- javascript - 代码中的哪个函数有错误以及如何修复代码以再次正常工作
- html - Safari密码建议更改输入框大小
- laravel - MongoDB StartSession 提交和回滚失败