How to retrieve parent objects by filtering from child objects in a Java stream

People are my root poja, and I have a list of phone numbers for my children

String firstName;

String lastName;

Long id;

List<String> phoneNumber = new ArrayList<>();

int age;


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

List<Person> personList = Arrays.asList(
    new Person("Abdul","Razak",27,50L,Arrays.asList("100","101","102")),new Person("Udemy","tut",56,60L,Arrays.asList("200","201","202")),new Person("Coursera",78,20L,Arrays.asList("300","301","302")),new Person("linked",14,10L,Arrays.asList("400","401","402")),new Person("facebook",24,5L,Arrays.asList("500","501","502")),new Person("covila",34,22L,Arrays.asList("600","602","604")),new Person("twitter",64,32L,Arrays.asList("700","702","704"))
);

List<String> list = personList.stream()
    .map(p -> p.getPhoneNumber().stream())
    .flatMap(inputStream -> inputStream)
    .filter(p -> p.contains("502"))
    .collect(Collectors.toList());

I want to retrieve a person whose number is equal to a specific string Can you do this by using streams?

List<String> list = personList.stream()
    .map(p -> p.getPhoneNumber().stream())
    .flatMap(inputStream -> inputStream)
    .filter(p -> p.contains("502"))
    .collect(Collectors.toList());

Simply put, how do I retrieve parent objects by filtering child objects?

Solution

personList.stream().filter((person)->person.getContacts().contains("100"))
personList.stream().filter((person)->person.getContacts().contains("100"))
                .collect(Collectors.toList());

Will give you a match

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>