Java – can I get an enumeration based on the value of its field?

I want to get a specific enumeration based on its field value

Enumeration:

public enum CrimeCategory {
    ASBO ("Anti Social BehavIoUr"),BURG ("Burglary"),CRIMDAM ("Criminal Damage And Arson"),DRUGS ("Drugs"),OTHTHEFT ("Other Theft"),PUPDISOR ("Public Disorder And Weapons"),ROBBERY ("Robbery"),SHOPLIF ("Shoplifting"),VEHICLE ("Vehicle Crime"),VIOLENT ("Violent Crime"),OTHER ("Other Crime");

    private  String category;


    private CrimeCategory (String category) {
        this.category = category;
    }

    public String returnString() {
        return category; 
    }
}

Get new enumeration:

aStringRecivedFromJson = "Anti Social BehavIoUr"
CrimeCategory crimeCategoryEnum;
crimeCategoryEnum = CrimeCategory.valueOf(aStringRecivedFromJson);

I've been trying to find a way to provide an enumeration above so that it can be distributed in the HashMap along with other crime information Expected accomplishment: ASBO

Solution

For reference, here is an alternative solution to HashMap:

enum CrimeCategory {
  ASBO("Anti Social BehavIoUr"),BURG("Burglary"),CRIMDAM("Criminal Damage And Arson"),DRUGS("Drugs"),OTHTHEFT("Other Theft"),PUPDISOR("Public Disorder And Weapons"),ROBBERY("Robbery"),SHOPLIF("Shoplifting"),VEHICLE("Vehicle Crime"),VIOLENT("Violent Crime"),OTHER("Other Crime");

  private static final Map<String,CrimeCategory> map = new HashMap<>(values().length,1);

  static {
    for (CrimeCategory c : values()) map.put(c.category,c);
  }

  private final String category;

  private CrimeCategory(String category) {
    this.category = category;
  }

  public static CrimeCategory of(String name) {
    CrimeCategory result = map.get(name);
    if (result == null) {
      throw new IllegalArgumentException("Invalid category name: " + name);
    }
    return result;
  }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>