Abdul Razak AK
Abdul Razak AK

Reputation: 415

How to retrieve parent object by filtering out from the child object in java stream

Person is my root POJA and I have list of phone number of as my child object.

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", "tut", 78, 20L, Arrays.asList("300", "301", "302")),
    new Person("linked", "tut", 14, 10L, Arrays.asList("400", "401", "402")),
    new Person("facebook", "tut", 24, 5L, Arrays.asList("500", "501", "502")),
    new Person("covila", "tut", 34, 22L, Arrays.asList("600", "602", "604")),
    new Person("twitter", "tut", 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 would like to retrieve person whose numbers equals to specific string. Is it possible to achieve this by using stream ?.

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

In simple, How to retrieve parent object by filtering child object ?

Upvotes: 5

Views: 3982

Answers (3)

Mehraj Malik
Mehraj Malik

Reputation: 15874

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

Will give you the matched Person.

Upvotes: 4

hiren
hiren

Reputation: 1812

Try this List<Person> collect = personList.stream().filter(person -> person.phoneNumber.contains("502")).collect(Collectors.toList());

Upvotes: 1

Naman
Naman

Reputation: 32038

I would like to retrieve person whose numbers equals to specific string

List<Person> list = personList.stream().filter(p -> p.getPhoneNumber().contains("502"))
                     .collect(Collectors.toList())

This shall get you the list of Person whose list of phoneNumbers consists of "502" as a string.

Upvotes: 2

Related Questions