在流式列表中过滤内部对象列表。

huangapple go评论77阅读模式
英文:

Filter internal list of objects in a stream of List

问题

我有一列人物物件

public class Person {
    private String name;
    private List<Animal> animals;
}

其中有一列动物物件:

public class Animal {
    private String name;
}

我试着根据特定名字创建一个新的列表,我试着只提取那些名字特定的人物

List<Person> filteredPeople = people.stream()
                .filter(e -> e.getName().equals("John")).collect(Collectors.toList());

是否可以添加更多的过滤条件,以及我如何访问人物内部的动物列表,以便我可以按动物的名称进行过滤 - 例如,如果人物内的任何动物的名称是"Lucky",也将这个人物物件放入新的列表?

看起来这不是一个有效的想法:

.filter(e -> e.getAnimals().stream().filter(f -> f.getName().equals("lucky")))
英文:

I have List of Person objects

public class Person {
    private String name;
    private List&lt;Animal&gt; animals;
}

Which have list of animal objects:

public class Animal {
    private String name;
}

I am trying to create a new list out of it and I am trying to extract only those Person who have a specific name

List&lt;Person&gt; filteredPeople = people.stream()
                .filter(e -&gt; e.getName().equals(&quot;John&quot;)).collect(Collectors.toList());

Is it possible to add one more filter and how do I access the Animal list inside the person so I can filter by the animal name - for example if any the Animals(inside Person) name is "Lucky" to also put this Person object inside the new list?

Looks like this is not a valid idea:

.filter(e -&gt; e.getAnimals().stream().filter(f -&gt; f.getName().equals(&quot;lucky&quot;)))

答案1

得分: 1

你可以通过以下方式实现:

persons.stream()
    .filter(p -> p.getName().equals("John") || p.getAnimals().stream().anyMatch(a -> a.getName().equals("lucky")))
    .collect(Collectors.toList())
英文:

You can achieve this by

persons.stream()
    .filter(p -&gt; p.getName.equals(&quot;John&quot;) || p.getAnimals().stream().anyMatch(a -&gt; a.getName.equals(&quot;lucky&quot;)))
    .collect(Collectors.toList())

huangapple
  • 本文由 发表于 2020年5月3日 22:08:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/61575825.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定