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 ?
personList.stream().filter((person)->person.getContacts().contains("100"))
.collect(Collectors.toList());
Will give you the matched Person
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With