Java HashSet<>:如果HashSet包含非指定的值,则返回false [英] Java HashSet<> : Return false if HashSet contains values other than specified

查看:62
本文介绍了Java HashSet<>:如果HashSet包含非指定的值,则返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我从中提取了一个字符串列表,例如{"ADD","DEL","CHG","DEL","NA","ADD","BLAH","YAK",....}JSON请求并将其传递到哈希集上,以避免重复.如果HashSet除了"ADD","NA"或"both"以外的其他值,如何使我的函数返回false?任何帮助.

So I extracted a List of Strings e.g {"ADD","DEL","CHG","DEL","NA","ADD","BLAH","YAK",.... } from JSON Request and passed them onto a hashset to avoid duplicates. How do I get my function to return false if the HashSet has anything else other than "ADD" or "NA" or "both" ? Any Help Appreciated.

更新:在我的代码中,我只是在所有我可能认为不需要的值周围添加了一个NOT条件.我需要一个更有效的解决方案.

Update: In my code, I just added a NOT condition around all those values that I can possibly think of that I do not require.I need a more effective solution.

也:我的true()条件是ADD必须始终存在,而NA是可选的.除了必需的"ADD"和可选的"NA"之外,没有其他值必须存在.例如:

Also: My true() condition is that ADD must present at all times while NA is optional.No other values must be present other than the mandatory "ADD" and the optional "NA" . eg:

  1. {ADD}返回true
  2. {ADD,NA}返回true
  3. {ADD,DEL}返回false
  4. {DEL,YAK}返回false,等等.

下面的代码片段没有此项检查,我正在寻找最少冗长的最佳解决方案.

The below snippet doesn't have this check and i am looking for the best solution with least verbosity.

这是代码段.字符串列表作为参数传递给isAddOrNa().

Here's the snippet. The List of Strings are passed as an argument to isAddOrNa().

private boolean isAddOrNa(List<AllActions> allActions) {
    Set<String> actions = new HashSet<>();
    for (com.demo.Action action : allActions) {
        actions.add(action.getName());
    }
    return ((actions.size() <= 2) && (actions.contains("ADD") || actions.contains("NA"))) &&
            !(actions.contains("DEL") || actions.contains("CHG") || actions.contains("BLAH") || actions.contains("YAK"));
}

推荐答案

private boolean isAddOrNa(List<AllActions> allActions) {
    Set<String> actions = new HashSet<>();
    for (com.demo.Action action : allActions) {
        actions.add(action.getName());
    }
    return actions.contains("ADD") && ((actions.contains("NA") && actions.size() ==2) || (!actions.contains("NA") && actions.size() ==1));
}

最小化条件.这有帮助吗?

Minimized the conditions. Does this help?

这篇关于Java HashSet&lt;&gt;:如果HashSet包含非指定的值,则返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆