Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

Java HashSet<> : Return false if HashSet contains values other than specified

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.

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.

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} returns true
  2. {ADD,NA} return true
  3. {ADD,DEL} returns false
  4. {DEL,YAK} return false, etc.

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

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"));
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...