2 回答

TA貢獻(xiàn)1830條經(jīng)驗 獲得超3個贊
有很多方法可以做到這一點。如果主要問題是代碼看起來不整潔,我建議將過濾謂詞分解到它自己的方法中。那么這只是用該謂詞進(jìn)行調(diào)用的問題Stream.anyMatch
。例如:
public class ResponseVo {
? ? public static void main(String[] args) {
? ? ? ? ResponseVo response = ... // Obtain response
? ? ? ? boolean anyMatch = response.dateTimeObj
? ? ? ? ? ? .stream().anyMatch(dtvo -> exists(dtvo, "2019-08-27", "A"));
? ? }
? ? List<DateTimeVo> dateTimeObj;
? ? private static boolean exists(DateTimeVo dtvo,?
? ? ? ? String date, String code) {
? ? ? ? return dtvo.dateObj.equals(date) &&?
? ? ? ? ? ? dtvo.timeList.stream().anyMatch(tvo -> tvo.code.equals(code));
? ? }
}

TA貢獻(xiàn)1827條經(jīng)驗 獲得超9個贊
您可以結(jié)合使用Predicate,創(chuàng)建易于維護(hù)的謂詞集合,然后按以下方式應(yīng)用所有謂詞:
@Test
public void filterCollectionUsingPredicatesCombination(){
List<Predicate<MyObject>> myPredicates = new ArrayList<Predicate<MyObject>>();
myPredicates.add(myObject -> myObject.myString.startsWith("prefix"));
myPredicates.add(myObject -> myObject.myInstant.isBefore(Instant.now()));
myPredicates.add(myObject -> myObject.myInt > 300);
List<MyObject> result = myData.stream() // your collection
.filter(myPredicates.stream().reduce(x->true, Predicate::and)) // applying all predicates
.collect(Collectors.toList());
assertEquals(3, result.size()); // for instance
}
添加回答
舉報