Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 536
SteroidKing666 Avatar asked Nov 21 '18 06:11

SteroidKing666


People also ask

Can enums be generic?

Enum, Interfaces, and GenericsThe enum is a default subclass of the generic Enum<T> class, where T represents generic enum type. This is the common base class of all Java language enumeration types.

Can a method return enum?

An enum is a (special type of) class, so you should declare it as the return type of your method.

Can we use enum as array?

Enums are value types (usually Int32). Like any integer value, you can access an array with their values. Enum values are ordered starting with zero, based on their textual order. MessageType We see the MessageType enum, which is a series of int values you can access with strongly-typed named constants.

Which method returns an array of the enum's constants?

Method Detail Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows: for (AccessMode c : AccessMode.


Video Answer


1 Answers

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]
like image 67
Eran Avatar answered Oct 09 '22 09:10

Eran