0

I want to simplify the given code (actually the mapping of status):

private static final Map<SomeStatusEnum, OtherStatusEnum> STATUS_ENUM_MAP = Map.of(
      SomeStatusEnum.A, OtherStatusEnum.OK,
      SomeStatusEnum.B, OtherStatusEnum.NOK,
      SomeStatusEnum.C, OtherStatusEnum.NOK,
      SomeStatusEnum.D, OtherStatusEnum.NOK,
      SomeStatusEnum.E, OtherStatusEnum.NOK,
      SomeStatusEnum.F, OtherStatusEnum.NOK
  );

to a structure like:

private static final Map<SomeStatusEnum, OtherStatusEnum> STATUS_ENUM_MAP = Map.of(
     SomeStatusEnum.A, OtherStatusEnum.OK,
     *ALL OTHER SomeStatusEnums*, OtherStatusEnum.NOK     
 );

so that only SomeStatusEnum.A points to OtherStatusEnum.OK while all others point to OtherStatusEnum.NOK without writing all of them in the map explicitly.

Anyone an idea?

ernest_k
  • 44,416
  • 5
  • 53
  • 99
DerBenniAusA
  • 727
  • 1
  • 7
  • 13
  • Are you required to use a map? Why not use method like `OtherStatusEnum statusMapping(SomeStatusEnum en){ switch (en){ case A: return OtherStatusEnum.OK; default: return OtherStatusEnum.NOK; } }`? Here `*ALL OTHER SomeStatusEnums*` are handled by `default:` case. If you have many cases which should be mapped as OK you can something like `case A: case B: return OtherStatusEnum.OK;` (see [Using two values for one switch case statement](https://stackoverflow.com/q/16706716)) – Pshemo Dec 18 '19 at 12:26
  • perfectly solved, it will use this approach :-) – DerBenniAusA Dec 18 '19 at 12:30

1 Answers1

1

Not sure that this is what you're looking for - but you can use a map with the getOrDefault function like this:

private static final Map<SomeStatusEnum, OtherStatusEnum> STATUS_ENUM_MAP = 
  Map.of(SomeStatusEnum.A, OtherStatusEnum.OK);

and then use the map as:

STATUS_ENUM_MAP.getOrDefault(value, OtherStatusEnum.NOK)
Yonatan Karp-Rudin
  • 1,056
  • 8
  • 24