java - 如何使用多个条件从集合列表中过滤

标签 java filter stream reduce predicate

如何使用最少的代码比较集合列表并检查特定复合条件(&& 不是 ||)是否匹配?

例如,我想验证 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/

相关文章:

java - 如何在 Java 中将打开的套接字分派(dispatch)给线程?

c - C语言中的用户输入过滤,例如避免字母和符号

stream - ffmpeg - 将网络摄像头连续流式传输到单个 .jpg 文件(覆盖)

node.js - 使用 node.js http2 模块的服务器发送事件 - 我应该如何将它与流/pushStream 一起使用?

stream - Gstreamer - appsrc 推送模型

java - RxJava : update result of call with results of subsequent calls

java - 如何向 CompositeItemProcessor 注册监听器

java - 我可以相信 System.nanoTime() 每次调用都会返回不同的值吗?

json - elasticsearch嵌套查询

java - web.xml 中的 "forward"与过滤器中的 0x104567910 有什么区别