根据NotNull条件进行过滤

时间:2019-01-14 21:50:44

标签: java

所以我试图根据一些键过滤掉jsonResponse……如果该块具有所有提供的键,则返回该块

伪代码是这样的:

public Object filterSomething(String key1, String key2, String key3){


    for (Map<Object, Object> singleBlock : (List<Map<Object, Object>> someJsonResponse)){
        if (singleBock.IncludesAllNotNullKeys) {
            return singleBlock
        }
    }

}

请注意,任何key都可以为Null(由最终用户指定),在这种情况下,我将基于非null的结果进行过滤。

很明显,我可以检查哪些不是NotNull,然后有多个for循环(但是看起来很乱!)……类似这样:

public Object filterSomething(String key1, String key2, String key3){

    if (key1 != Null && key2 != Null && key3 != Null) {
        for (Map<Object, Object> singleBlock : (List<Map<Object, Object>> someJsonResponse)){
            if (singleBock.IncludesAllKeys()) {
                return singleBlock
            }
        }
    }

    if (key1 != Null && key2 != Null) {
        for (Map<Object, Object> singleBlock : (List<Map<Object, Object>> someJsonResponse)){
            if (singleBock.IncludesBothKeys()) {
                return singleBlock
            }
        }
    }

    ...

}

关于如何正确处理此案是否有任何建议?

1 个答案:

答案 0 :(得分:0)

当您检查单个块是否包含该键时,我只会在逻辑中检查null:singleBock.IncludesAllNotNullKeys

该方法可能如下所示:

private boolean includesAllNotNullKeys(Object singleBlock, String key1, String key2, String key3) {
    boolean check1 = key1 == null || singleBlock.contains(key1);
    boolean check2 = key2 == null || singleBlock.contains(key2);
    boolean check3 = key3 == null || singleBlock.contains(key3);
    return check1 && check2 && check3;
}

当然,这是完全根据您的问题定制的。对于更可重用的通用方法,您可以将键作为var-args或List<String>处理,并且该方法可以相应地迭代和中断。