I have a enum with some values.
Is there a way I can add all the values
into a map inside that same enum class?
Where the Key for the map being the id and the map Value being a enum value.
public enum Snack{
CAKE(1, "Cake", R.drawable.ic_cake),
CHIPS(2, "Chips", R.drawable.ic_chips),
ICE_CREAM(3, "Ice cream", R.drawable.ice_cream)
private final int id;
private final String name;
private final int icon;
private static final Map<Integer, Snack> map;
static{
//load all enum values into map
}
Snack(int id, String name, int icon){
this.id = id;
this.name = name;
this.icon = icon;
}
public static Snack getSnackWithId(int id){
return map.get(id);
}
}
>Solution :
You can iterate over the values() of the enum.
private static final Map<Integer, Snack> map = new HashMap<>();
static{
for (Snack snack: Snack.values())
map.put(snack.id, snack);
}
Alternatively, in one statement:
private static final Map<Integer, Snack> map = Arrays.stream(Snack.values())
.collect(Collectors.toMap(s -> s.id, Function.identity()));