Sankar
Sankar

Reputation: 369

How to match a java enum

I've an enum like this:

public enum ChartType
{   
    TABLE(0, false), BAR(1, false), COLUMN(3, false)
    private int type;
    private boolean stacked;
    ChartType(int type, boolean stacked)
    {
        this.type = type;
        this.stacked = stacked;
    }
    public int getType()
    {
        return type;
    }
    public boolean isStacked()
    {
        return this.stacked;
    }
}

I get a charttype (int values like 0,1,3) from the request and want the matching input

Upvotes: 2

Views: 9704

Answers (5)

gaston
gaston

Reputation: 498

If you use java 8, use stream() and filter()

int value =2;
Optional<ChartType> chartType = Arrays.asList(ChartType.values()).stream().
filter(c -> c.type == value).findFirst();
if(chartType.isPresent()){
      ChartType chartType =chartType.get();
     //
}

Upvotes: 2

Pshemo
Pshemo

Reputation: 124215

You can add map in your enum to store relationship between type and specific enum value. You can fill it once in static block after all values will be created like:

private static Map<Integer, ChartType> typeMap = new HashMap<>();

static{
    for (ChartType chartType: values()){
        typeMap.put(chartType.type, chartType);
    }
}

then you can add method which will use this map to get value you want, or null if there isn't any

public static ChartType getByType(int type) {
    return typeMap.get(type);
}

You can use it like

ChartType element = ChartType.getByType(1);

Upvotes: 5

owenrb
owenrb

Reputation: 535

Define new method:

public ChartType valueOf(int id) {
   switch(id) {
   case 1:
      return TABLE;
   case 2:
      return BAR;
   case 3:
      return COLUMN;
   }

   return null;
}

Example:

ChartType.valueOf(1) // TABLE

Upvotes: 2

user489041
user489041

Reputation: 28294

Something along these lines. Not sure if syntax is 100 percent, but it demos the idea.

public ChartType getChartypeForValue(int value)
    for(ChartType type : ChartType.values()){
        if(type.getType()  == value){
            return type;
        }
    }
    return null;
}

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1500055

You should create a static method to retrieve a type by number. With just a few charts like this, it's simplest to do that by just running through all the options. For larger enums, you could create a map for quick lookup. The only thing to watch for here is that any static initializers aren't run until after the values have been created.

Simple approach:

public static ChartType fromType(int type) {
    // Or for (ChartType chart : ChartType.getValues())
    for (ChartType chart : EnumSet.allOf(ChartType.class)) {
        if (chart.type == type) {
            return chart;
        }
    }
    return null; // Or throw an exception
}

Upvotes: 4

Related Questions