使用子类的值过滤类的流 [英] Filter a stream of a class using a value of subclass

查看:58
本文介绍了使用子类的值过滤类的流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父类Company,它有一个Employee对象的列表.我需要创建一个Parent类的流,该流具有一个Employee并提到了电话号码.

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.

推荐答案

anyMatch用作谓词而不是flatMap作为

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

这篇关于使用子类的值过滤类的流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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