家长班:
public class Person {
String firstName;
String lastName;
Long id;
List phoneNumber = new ArrayList<>();
int age;
public Person(String firstName, String lastName, int age, Long id, List phone) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.id = id;
this.phoneNumber = phone;
}
儿童电话对象(第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;
}
}
我正在尝试获取其电话对象类型为home且其编号应包含“888”的person对象.
List 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());
从上面的流代码,我能够获得电话对象.但是如何在同一个函数中获取该手机对象的父对象呢?
我试过这种方式,我为非匹配的对象获取null.
List finalList = personList.stream().map( per -> {
List phones = per.getPhoneNumber();
Optional ph = phones.stream().filter(p -> p.number.contains("888") && p.type.equals("HOME")).findAny();
if(ph.isPresent())
return per;
return null;
}).collect(Collectors.toList());