英文:
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<Animal> 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<Person> filteredPeople = people.stream()
.filter(e -> e.getName().equals("John")).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 -> e.getAnimals().stream().filter(f -> f.getName().equals("lucky")))
答案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 -> p.getName.equals("John") || p.getAnimals().stream().anyMatch(a -> a.getName.equals("lucky")))
.collect(Collectors.toList())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论