Parent class:
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;
}
Child Phone Object (Level 1):
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;
}
}
I am trying to get a person object whose telephone object type is home, and its number should contain "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());
From the above thread code, I can get the phone object. But how to get the parent of this telephone object in the same function ?.
I tried this way and I get null for disparate objects.
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());
source
share