Java 8让所有员工的地址都以P开头 [英] Java 8 get all employee having address start with P

查看:72
本文介绍了Java 8让所有员工的地址都以P开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的雇员和地址类别如下

I have employee and address class as below

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开头的城市的员工

Using java 8 filter I want to print all employees who are having city starting with P

要添加到以下代码中以获取该过滤后地址的emp的内容

What to add to below code to get emp of that filtered address

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

谢谢.

推荐答案

filter中使用anyMatch而不是map ping:

Use anyMatch in filter instead of mapping :

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

这篇关于Java 8让所有员工的地址都以P开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆