New*_*ddy 5 java filter java-8 java-stream
我有员工和地址类如下
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
}
Run Code Online (Sandbox Code Playgroud)
使用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);
Run Code Online (Sandbox Code Playgroud)
提前致谢。
使用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
Run Code Online (Sandbox Code Playgroud)
Employee如果要打印Employee具有通过过滤条件的地址的s,则不应将实例映射到它们的地址:
employees.stream()
.filter(e -> e.getAddresses()
.stream()
.anyMatch(addr -> addr.getCity().startsWith("p")))
.forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
请注意,如果您要做的只是使用 迭代它,则没有理由将其收集Stream到 a 中。ListListforEach
| 归档时间: |
|
| 查看次数: |
3163 次 |
| 最近记录: |