2 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個(gè)贊
從您的問(wèn)題給出的代碼開(kāi)始:
List<Predicate<Person>> predicates = Arrays.asList(agePredicate, dobPredicate, namePredicate);
我們可以根據(jù)他們匹配的謂詞數(shù)量對(duì)人員列表進(jìn)行排序:
List<Person> sortedListOfPeopleByPredicateMatchCOunt =
listPersArrays
.asList(listPersons)
.stream()
.sorted(
Comparator.comparingLong(p -> predicates.stream().filter(predicate -> predicate.test(p)).count()))
// Reverse because we want higher numbers to come first.
.reversed())
.collect(Collectors.toList());

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
只是上述答案的擴(kuò)展,如果您的目標(biāo)是過(guò)濾匹配盡可能多條件的集合,您可以創(chuàng)建一個(gè)組合Predicate<Person>,然后將其用于過(guò)濾。
鑒于您的謂詞列表:
List<Predicate<Person>> predicates = Arrays.asList(agePredicate, dobPredicate, namePredicate);
復(fù)合謂詞可以這樣創(chuàng)建:
Predicate<Person> compositPredicate = predicates.stream()
.reduce(predicate -> false, Predicate::or);
注意:由于歸約操作需要一個(gè)標(biāo)識(shí)值,并且如果任何一個(gè)謂詞結(jié)果為or ,Predicate<>類的操作不會(huì)應(yīng)用任何進(jìn)一步的謂詞true,我已將其用作predicate -> false標(biāo)識(shí)值。
現(xiàn)在,過(guò)濾集合變得更容易和更干凈:
List<Person> shortListPersons = persons.stream()
.filter(compositPredicate)
.collect(Collectors.toList());
添加回答
舉報(bào)