gpt4 book ai didi

java - 使用子类的值过滤类的流

转载 作者:行者123 更新时间:2023-12-02 01:24:46 26 4
gpt4 key购买 nike

我有一个父类Company,它有一个Employee对象列表。我需要创建一个 Parent 类的流,该类有一个带有上述电话号码的 Employee

Company cmp1 = new Company();
cmp1.setName("oracle");

Company cmp2 = new Company();
cmp1.setName("Google");

Employee emp1 = new Employee();
emp1.setName("David");
emp1.setPhone("900");
Employee emp2 = new Employee();
emp2.setName("George");
emp2.setPhone("800");
Employee emp4 = new Employee();
emp4.setName("BOB");
emp4.setPhone("300");
Employee emp5 = new Employee();
emp5.setName("taylor");
emp5.setPhone("900");

List<Employee> cmp1EmpList1 = new ArrayList<Employee>();
cmp1EmpList1.add(emp1);
cmp1EmpList1.add(emp2);
cmp1.setEmployees(cmp1EmpList1);

List<Employee> cmp1EmpList2 = new ArrayList<Employee>();
cmp1EmpList2.add(emp4);
cmp1EmpList2.add(emp5);

cmp2.setEmployees(cmp1EmpList2);

List<Company> companies = Arrays.asList(cmp1, cmp2);

为了检索流,我尝试添加以下代码

List<Company> companiesWithEmployeesphone800 = companies.stream()
.filter(loc -> loc.getEmployees()
.stream()
.flatMap(locnew -> locnew.getPhone()
.equalsIgnoreCase("800"))
)
.collect(Collectors.toList());

但收到了不兼容的类型。

最佳答案

使用anyMatch作为谓词而不是flatMap:

List<Company> companiesWithEmployeesphone800 =
companies.stream()
.filter(loc -> loc.getEmployees().stream()
.anyMatch(locnew -> locnew.getPhone().equalsIgnoreCase("800")))
.collect(Collectors.toList());

关于java - 使用子类的值过滤类的流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57098707/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com