java - 如何根据子对象字段获取父对象

标签 java java-8 java-stream

父类:

public class Person {
    String firstName;
    String lastName;
    Long id;
    List<Phone> phoneNumber = new ArrayList<>();
    int age;

    public Person(String firstName, String lastName, int age, Long id, List<Phone> phone) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.id = id;
        this.phoneNumber = phone;
    }

子电话对象(第一级):

public class Phone {
    String number;
    String type;
    Long id;
    public Phone(String number, String type, Long id) {
        super();
        this.number = number;
        this.type = type;
        this.id = id;
    }
}

我正在尝试获取电话对象类型为 home 且其号码应包含“888”的人员对象。

List<Phone> list = personList.stream().map(p -> p.getPhoneNumber().stream()).
                flatMap(inputStream -> inputStream).filter(p -> p.number.contains("888") && p.type.equals("HOME")).collect(Collectors.toList());

        System.out.println(list.toString());

从上面的流代码中,我可以得到电话对象。但是如何在同一函数本身中获取该电话对象的父对象?

我尝试过这种方式,但对于不匹配的对象,我得到的是 null。

List<Person> finalList = personList.stream().map( per -> {
            List<Phone> phones = per.getPhoneNumber();
            Optional<Phone> ph = phones.stream().filter(p -> p.number.contains("888") && p.type.equals("HOME")).findAny();
        if(ph.isPresent())
            return per;
        return null;
        }).collect(Collectors.toList());

最佳答案

List<Person> result = personList.stream()
    .filter( person -> person.phoneNumber.stream()
                             .anyMatch(phone -> phone.type.equals("HOME") && 
                                                phone.number.contains("888"))
    .collect(Collectors.toList());

您正在寻找的是电话的。它会成功的。

让人们拥有他们的手机,您现在可以移除那些不符合条件的手机。

List<Person> result = personList.stream()
        .filter( person -> person.phoneNumber.stream()
                                 .anyMatch(phone -> phone.type.equals("HOME") && 
                                                    phone.number.contains("888"))
        .map(person -> {
            List<Phone> phones = person.phoneNumber.stream()
                                    .filter(phone -> phone.type.equals("HOME") && 
                                                    phone.number.contains("888"))
                                    .collect(Collectors.toList());
            return new Person(person.firstName, person.lastName, person.age, person.id, phones);
        })
        .collect(Collectors.toList());

关于java - 如何根据子对象字段获取父对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46542106/

相关文章:

java - 使用 Lingpipe 进行词级语言模型

java - 最终变量和编译时间常数之间的差异

java - 无法在 WebSphere 中以编程方式创建 JMS 主题

java - Stream#limit 可以返回比预期更少的元素吗?

java - SWT Combo 调整下拉列表大小(显示更多项目)

此处不应引用 Java 方法

java - 如何在 Windows 64 位操作系统中安装 openJdk 8

java - 如何迭代谓词列表

Java 8 将 for 循环和值的总和转换为流/lambda?

java - 生成可能的 boolean 组合的最优雅的方式