5

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 ?

0

3 Answers 3

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

Will give you the matched Person.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Assessed too highly by using flatmap to get child object
2

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.

Comments

1

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

1 Comment

to get person phonenumber list... you can also get it by getter method or by calling . operator. Have you tried this code ? It is working fine.. please check before commenting

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.