如何通过从java流中的子对象过滤来检索父对象

时间:2017-10-03 08:32:01

标签: java java-8 java-stream

人是我的根POJA,我有电话号码列表作为我的孩子对象。

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());

我想检索其数字等于特定字符串的人。是否可以通过使用流来实现这一目标。

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

简单来说,如何通过过滤子对象来检索父对象?

3 个答案:

答案 0 :(得分:4)

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

会为您提供匹配的Person

答案 1 :(得分:2)

  

我想找回其数字等于具体数字的人   串

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

这将为您提供Person的列表,其中phoneNumber的列表包含&#34; 502&#34;作为一个字符串。

答案 2 :(得分:1)

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