0

I am writing a web application where in I need to have a lot of fixed values in the system to support operations and UI.I figured out it's better to put them in an Enum and group them using EnumSet as described in the Snippet below.

Now what I need is a way to retrieve only the values from a particular enum set based on the String input I provide.

For example: A method getFixedValues(identifier); where in identifer="VehicleType" should return CAR("10"), BIKE("20"),TRUCK("30")

I tried few things but not able to work my way out through EnumSet.

public enum MyEnum {

CAR("10"),
BIKE("20"),
TRUCK("30"),

XML("100"),
EDI("300"),

APP1("A1"),
APP2("A2");

String value;

private MyEnum() {

}

private MyEnum(String value) {
    this.value = value;
}

public static EnumSet<MyEnum> VehicleType = EnumSet.of(CAR, BIKE, TRUCK);
public static EnumSet<MyEnum> MessageType = EnumSet.of(XML, EDI);
public static EnumSet<MyEnum> ApplicationType = EnumSet.of(APP1, APP2);}
nocoder
  • 89
  • 1
  • 7

1 Answers1

0

Your enum values seems really not related between them.
You mix vehicle types with data formats and a kind of app identifiers :

CAR("10"),
BIKE("20"),
TRUCK("30"),

XML("100"),
EDI("300"),

APP1("A1"),
APP2("A2");

I thin that defining a distinct enum for each one of these concepts is clearer.

Beyond this question of conception, to address your need you could add a new field identifier to define a MyEnum value.
The type of the field could be another public enum declared in this enum.

public enum MyEnum {

  CAR("10", Type.VEHICLE_TYPE),
  BIKE("20", Type.VEHICLE_TYPE),
  TRUCK("30", Type.VEHICLE_TYPE),

  XML("100",  Type.DATE_FORMAT),
  EDI("300", Type.DATE_FORMAT),),
   ...

  public enum Type{
     VEHICLE_TYPE, DATE_FORMAT, ...
  }

  String value;
  Type type;

  private MyEnum(String value, Type type) {
    this.value = value;
    this.type = type;
  }

  public static List<MyEnum>  getFixedValues(Type type){
   List<MyEnum> enums = new ArrayList<>();
   for (MyEnum myEnum : values()){
      if (myEnum.type == type){
         enums.add(myEnum);
       }
    }
    return enums;
  }

...
}

Then you could declare your getFixedValues(Type type) method :

   public static List<MyEnum>  getFixedValues(Type type){
       List<MyEnum> enums = new ArrayList<>();
       for (MyEnum myEnum : values()){
          if (myEnum.type == type){
             enums.add(myEnum);
           }
        }
       return enums;
     }

You could of course store the list in a static field to avoid to do the iteration at each call.

davidxxx
  • 125,838
  • 23
  • 214
  • 215