如何使用最少的代码比较集合列表并检查特定复合条件(&& 不是 ||)是否匹配?
例如,我想验证 startDateObj=2019-08-27, timeCode=A 和 endDateObj=2019-08-28, timeCode=D 是否同时存在于响应列表中。
我有以下类(class)
ResponseVo {
List<DateTimeVo> dateTimeObj;
}
DateTimeVo {
String dateObj;
List<TimeVo> timeList;
}
TimeVo {
String code;
String displayInformation;
}
示例输出
{
"dateTimeObj": [
{
"dateObj": "2019-08-27",
"timeList": [
{
"code": "A",
"displayInformation": "Do A Act"
},
{
"code": "B",
"displayInformation": "Do B Act"
}
]
},
{
"dateObj": "2019-08-28",
"timeList": [
{
"code": "C",
"displayInformation": "Do C Act"
},
{
"code": "D",
"displayInformation": "Do D Act"
}
]
}
]
}
目前,我通过调用可选的post每个过滤器并首先查找来实现它,这看起来非常不整洁和麻烦。
最佳答案
有很多方法可以做到这一点。如果主要问题是代码看起来不整洁,我建议将过滤谓词分解到它自己的方法中。那么只需调用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));
}
}
关于java - 如何使用多个条件从集合列表中过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57658602/