Filter a stream of a class using a value of subclass

浪子不回头ぞ 提交于 2021-02-02 09:39:26

问题


I have a parent class Company which has a list of Employee objects. I need to create a stream of Parent class who has an Employee with the phone number mentioned.

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);

To retrieve the stream I have tried adding the below code

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

but received incompatible types.


回答1:


Use anyMatch for a predicate instead of flatMap as:

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


来源:https://stackoverflow.com/questions/57098707/filter-a-stream-of-a-class-using-a-value-of-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!