Java 流过滤器匹配多个条件谓词

Java Stream filter match multiple criteria predicate

给定人员列表:

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

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

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

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

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

有什么想法吗?谢谢!

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

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