Search code examples
javaenumsguavaapache-commons

Elegant way to validate keyset of a map with an enum?


I have a map in which I need to validate keyset of map with my enum. I have an enum class as shown below:

  public enum Tag {
    rename, duplicate, process, limit, encode, decode;
  };

Now keyset of map should have values from above enum. If my keyset contains value which is not there in the enum, then I want to throw IllegalArgumentException with the value missing from my enum.

Below is my code:

  public Processor(Map<String, String> tasks) {
    Set<String> keyset = tasks.keySet();
    for (String tag : keyset)
      checkArgument(!EnumUtils.isValidEnum(Tag.class, tag), "unknown tag found '%s'.", tag);
  }

As you can see I am iterating keyset and doing Preconditions.checkArgument check. If it is not there then it will throw IllegalArgumentException. I am sure throwing message can be improved though.

My question is: Is there any better way to do the same thing as compared to what I am doing? Do I have to iterate the keyset in the for loop to do the check? or Is there any one liner or any other better way to do this validation?

I am using Java7.


Solution

  • You're doing a bit too much work. Realistically speaking, all you need to do is bind your key in your map to Tag.

    public Processor(Map<Tag, String> tasks) {
        // processor logic    
    }
    

    This guarantees that the keys in the map passed in can only ever be Tag. You also don't require the exception in this scheme, since your code will fail to compile if an invalid key is passed. Also, since it's an enum, you're not going to get any keys that aren't in that enum.

    If you're processing a list of strings and you can't get the enum directly, then you can use Tag.valueOf("<string value here>") to convert it.