如何匹配java枚举

时间:2015-03-06 17:18:26

标签: java enums

我有一个这样的枚举:

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;
    }
}

我从请求中得到一个charttype(int值,如0,1,3),并且想要匹配的输入

5 个答案:

答案 0 :(得分:5)

这些方面的东西。不确定语法是否是百分之百,但它会演示这个想法。

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

答案 1 :(得分:4)

您应该创建一个静态方法来按编号检索类型。只需几张这样的图表,只需运行所有选项,最简单的方法就是这样做。对于较大的枚举,您可以创建一个快速查找的地图。这里唯一需要注意的是,任何静态初始化程序都不会在之后运行值。

简单方法:

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
}

答案 2 :(得分:4)

您可以在枚举中添加地图,以存储type与特定枚举值之间的关系。在创建所有值之后,您可以在静态块中填充一次,如:

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

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

然后您可以添加将使用此地图获取所需值的方法,如果没有任何

,则为null
public static ChartType getByType(int type) {
    return typeMap.get(type);
}

您可以像

一样使用它
ChartType element = ChartType.getByType(1);

答案 3 :(得分:2)

如果您使用java 8,请使用stream()和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();
     //
}

答案 4 :(得分:0)

定义新方法:

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

   return null;
}

示例:

ChartType.valueOf(1) // TABLE