Home > Software design >  Iterate through a particular values of an enum
Iterate through a particular values of an enum

Time:07-09

I have the following enum -

public enum Colours {
      RED ("RED"),
      BLUE ("BLUE"),
      YELLOW ("YELLOW"),
      GREEN ("GREEN");

private String val;

Colours (String val) {
     this.val = val; }

How can I implement this to iterate through the values of enum?

CodePudding user response:

You could use the values() method to get all your enum's values as a list and run through that using a for-each

for (Colours colour : Colours.values()) {
    if (flag.equals(colour.val)) {
        // do something
    }
}

CodePudding user response:

You can iterate through the values of the enum and compare each one with your input. If you find a valid value you can return the enum.

    public static Colors getColorEnum(String value) {
        for (Colors c : Colors.values()) {
            if (value.equalsIgnoreCase(c.val)) {
                return c;
            }
        }
        //You can also throw a runtime exception if you want
        throw new RuntimeException("There was a problem with the color enum.");
    }

I personally use this approach in many situations. You can also use ordinal but i think it is obsolete.

  • Related