0

I have data like this

11 Crops
12 Plantation
13 Animal Husbandry
14 Fishery

I have tried to build an enum class like this:

public enum SubSectorEnum {
    Crops(11), 
    Plantation(12);
}

What I want is, if I have data 11 or 12, I want to convert it to Crops or plantation. My problem is, the data is stored in a database where I only have 11 or 12 as int. What I need is to convert from int 11 and 12 become Crops or Plantation. How to convert it?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
bigger
  • 1
  • 1
  • take a look at this https://stackoverflow.com/questions/3990319/storing-integer-values-as-constants-in-enum-manner-in-java – JavaMan Nov 11 '20 at 06:27

3 Answers3

1

There are two easy approaches you could use depends on logic you want to use

I would suggest to use second one

public enum SubSectorEnum {

    Crops(11), Plantation(12);

    public int id;

    SubSectorEnum(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    // 1 approach using switch 
    public SubSectorEnum convertIdToEnum(int id) {
        SubSectorEnum subSectorEnum = Crops; // Default
        switch (id) {
        case 11:
            subSectorEnum = Crops;
            break;
        case 12:
            subSectorEnum = Plantation;
            break;
        default:

            break;
        }
        return subSectorEnum;
    }

    // 2 approach using a map 
    private static final Map<Integer, SubSectorEnum> map = new HashMap<Integer, SubSectorEnum>();
    static {
        for (SubSectorEnum subSectorEnum : SubSectorEnum.values())
            map.put(subSectorEnum.getId(), subSectorEnum);
    }

    public static SubSectorEnum getEnumFromMap(int id) {
        return map.get(id);
    }

}

if you have only these two values in your DB and you are always getting either 11 or 12 and you don't plan to add anything in future you could use following method.

public SubSectorEnum getEnumById(int id) {
        return id==Crops.getId()?Crops:Plantation;
    }
devadrion
  • 216
  • 2
  • 6
1

A simple lookup which works if more enum values are added later can iterate through the values() list to find a suitable match:

public static SubSectorEnum findById(int id) {
    for (SubSectorEnum sse : values())
        if(id == sse.getId())
            return sse;
    throw new IllegalArgumentException("No SubSectorEnum with id "+id);
}
DuncG
  • 12,137
  • 2
  • 21
  • 33
-1

If I have understand what you need I think is this a enum with key-value:

enum SubSectorEnum  {

Crops(11, "Crops"), Plantation(2, "Plantation");

private final int key;
private final String value;

SubSectorEnum(int key, String value) {
    this.key = key;
    this.value = value;
}

public int getKey() {
    return key;
}
public String getValue() {
    return value;
}

}

So after you can get the value or the key:

SubSectorEnum.Crops.getValue();
SubSectorEnum.Crops.getKey();