How do I create a generic method to return an array of the enum values instead of its constants?

  • A+
Category:Languages

I have an enum with descriptions as String. This is the enum.

public enum tabs {     A("Actual data"),     B("Bad data"),     C("Can data"),     D("Direct data");      private String description;     tabs(String desc)     {         this.description = desc;     }       public String getDescription()     {         return this.description;     } } 

Now, if I need the data for A, I'd just do

tabs.A.description 

I am in the process of creating a generic method to return the values.

I have managed to utilize the below generic method to accept an enum type as the argument. It returns an array of the enum constants. But I actually want it to return an array of the values.. ie {"Actual data", "Bad data", "Can data", "Direct data"}.

public static String[] getActualTabs(Class<? extends Enum<?>> e)  {     return Arrays.stream(e.getEnumConstants()).map(Enum::name).toArray(String[]::new); } 

What options do I have to achieve this?

 


You can pass a mapper Function to map enum constants into Strings:

public static <T extends Enum<T>> String[] getActualTabs(Class<T> e, Function<? super T, String> mapper)  {     return Arrays.stream(e.getEnumConstants()).map(mapper).toArray(String[]::new); } 

Usage:

System.out.println(Arrays.toString(getActualTabs(tabs.class,tabs::getDescription))); 

Output:

[Actual data, Bad data, Can data, Direct data] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: