2 回答
TA贡献1830条经验 获得超3个赞
有很多方法可以做到这一点。如果主要问题是代码看起来不整洁,我建议将过滤谓词分解到它自己的方法中。那么这只是用该谓词进行调用的问题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贡献1827条经验 获得超9个赞
您可以结合使用Predicate,创建易于维护的谓词集合,然后按以下方式应用所有谓词:
@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
}
添加回答
举报