繁体   English   中英

检查 map 是否包含任何空值或键的最佳方法是什么?

[英]What is the optimal way to check if a map contains any empty values or keys?

我有一个存储一组问题和答案的 map。 不能有空答案的问题或空问题的答案。 下面是我如何初始化我的 map。

Optional<Map<String, String>> questionsAndAnswers();

我正在以下列方式验证问题/答案的空字符串。

questionsAndAnswers().ifPresent(questionsAndAnswers -> {
        if (questionsAndAnswers.isEmpty()) {
            throw new IllegalArgumentException("questions cannot be empty if present");
        } else if (questionsAndAnswers.keySet().contains("") || questionsAndAnswers.values().contains("")) {
            throw new IllegalArgumentException("Questions or answers cannot be empty");
        }
    });

有没有更好的方法来实现这一目标? 任何建议将不胜感激。

更新:我没有特别需要在两个不同的条件下完成这些检查。

你可以试试下面

    questionsAndAnswers().ifPresent(qna -> {
        if (qna.isEmpty() || qna.containsKey("") || qna.containsValue("")) {
            throw new IllegalArgumentException("Error Message Comes Here");
        }
    });

您抛出两个不同的异常,因此空的 map 和空的 Map 条目之间必须存在差异。

在第二个如果你应该检查,如果键或值是 null 或空:

questionsAndAnswers().ifPresent(pMap -> {
            if(pMap.isEmpty())
                throw new IllegalArgumentException();
            
            if(pMap.keySet().stream().anyMatch(pKey -> pKey == null || pKey.trim().isEmpty())
                    || pMap.values().stream().anyMatch(pValue -> pValue == null || pValue.trim().isEmpty()))
                throw new IllegalArgumentException();
        });

编辑:对于字符串,您可以使用 Apache Commons: https://stackoverflow.com/a/14721575/11050826

questionsAndAnswers().ifPresent(ConcurrentHashMap::new); 如果有任何 null 键/值,则抛出 NullPointerException

首先:您上面显示的代码包含一些语法错误。 您的 IDE 或编译器可能会帮助您解决这个问题。

您的 map 存储键/值对,其中键或值是问题,另一个是答案。 您要求的是不能存在空键或空值。

您可以遍历 map 并找到具有空值的条目。 你要对他们做些什么仍然取决于你......

for (Map.Entry<String, String> entry: questionsAndAnswers) {
    if (entry.getValue()==null || entry.getValue().isBlank()) {
        // here do what you need to do with an emty value
        // removing that from the map may be thrilling while you loop over it
    }
}

解决此问题后,您可能需要关心 null 或空问题。 文档说“将键映射到值的 object。map 不能包含重复的键;每个键可以 map 到最多一个值。” 这意味着最多有一个空问题。 要找到它,您只需这样做

questionsAndAnswers.get(null); // unlikely to reveal anything at all
questionsAndAnswers.get("");   // there you go, now put this answer again with the
                               // right question. 
questionsAndAnswers.remove();  // finally remove the empty question from the map

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM