Home > Net >  Iterate through a particular values of an enum to check a condition
Iterate through a particular values of an enum to check a condition

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

I am checking the below conditions on this enum as shown -

public static boolean flagValue (String flag) {
    return !String.valueOf(Colours.RED).equals(flag);
}


public static boolean colourStatus (String flag) {
    return !String.valueOf(Colours.BLUE).equals(flag)
             && !String.valueOf(Colours.YELLOW).equals(flag)
              && !String.valueOf(Colours.GREEN).equals(flag)
}

How can I implement this to check the conditions using a for-loop?

EDIT : I already tried this for-loop, but it doesn't seem to send the correct response

public static boolean checkFlag (String flag) {
    for(Colours c : Colours.values()) {
           if (!String.valueOf(c).equals(flag)) {
              return true; 
            }
      return false;
    }
}

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