gpt4 book ai didi

filter - Java Stream 过滤器匹配多个条件谓词

转载 作者:行者123 更新时间:2023-12-01 00:16:54 61 4
gpt4 key购买 nike

给定一个 Person 列表:

class Person {
private Integer id;
private Integer age;
private String name;
private Long lat;
private Long lont;
private Boolean hasComputer;
...

我想根据一组条件(例如年龄在 30 到 32 岁之间)返回前 5 名拥有计算机的人。

我想首先尝试匹配所有条件,但如果它不起作用,请尝试匹配其中任何一个。

我想到了一种类似的方法来做到这一点,例如全文搜索会使用排名系统吗?但我是 Stream 的新手,所以仍在寻找解决方案。

List<Person> persons = service.getListPersons();
persons.stream().filter(p -> p.getAge.equals(age) && p.hasComputer().equals(true)).allMatch()

有什么想法吗?谢谢!

  • 编辑:也许我可以创建一个谓词,例如

    Predicate predicate = p -> p.getAge() < 30 && e.name.startsWith("A");

并首先尝试匹配所有条件,如果不可能,则尝试匹配任何条件:

Persons.steam().allMatch(predicate).limit(5);
Person.steam().anyMatch(predicate).limit(5);

最佳答案

试试这个,

List<Person> filteredPeople = persons.stream()
.filter(p -> p.getAge() > 30)
.filter(p -> p.getAge() < 32)
.filter(p -> p.getHasComputer())
.limit(5).collect(Collectors.toList());

请注意,您可以根据需要添加额外的 filter 谓词。这只是完成工作的模板。

否则,如果您有一些动态数量的 Predicates 由一些外部客户端传递,您仍然可以这样做。

Predicate<Person> ageLowerBoundPredicate = p -> p.getAge() > 30;
Predicate<Person> ageUpperBoundPredicate = p -> p.getAge() < 32;
Predicate<Person> hasComputerPred = p -> p.getHasComputer();
List<Predicate<Person>> predicates = Arrays.asList(ageLowerBoundPredicate, ageUpperBoundPredicate,
hasComputerPred);
List<Person> filteredPeople = persons.stream()
.filter(p -> predicates.stream().allMatch(f -> f.test(p)))
.limit(5).collect(Collectors.toList());

关于filter - Java Stream 过滤器匹配多个条件谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51869685/

61 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com