Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to load enum values into a map inside the same enum class?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading