convert enum to list of names in java

Viewed 86

I have an enum as defined below. I need to convert it to a list of string which looks like ["In Progress","Cancelled","On Hold","Completed"]. How can I achieve that?

public static enum STATUS {
    IN_PROGRESS("In Progress"),
    CANCELLED("Cancelled"),
    ON_HOLD("On Hold"),
    COMPLETED("Completed");

    private String value;

    STATUS(String value) {
        this.value = value;
    }

    public String getValue() {
        return this.value;
    }
}
5 Answers

You can also use:

List<String> response = EnumSet.allOf(STATUS.class).stream()
        .map(STATUS::getValue)
        .toList();

To get all possible enumeration values of your STATUS enum, you can use.

STATUS.values()

You can then map them with getValue()

You can do it simple by:

List<STATUS> enumValues = Arrays.asList(STATUS.values());

or if you are using Java 8, something like this:

String[] enumValues = Stream.of(STATUS.values()).map(STATUS::name).toArray(String[]::new);

You can create an additional method in signature of your enum like that:

public static enum STATUS {
    IN_PROGRESS("In Progress"),
    CANCELLED("Cancelled"),
    ON_HOLD("On Hold"),
    COMPLETED("Completed");

    private String value;

    STATUS(String value) {
        this.value = value;
    }

    public String getValue() {
        return this.value;
    }

    public static List<String> getValueList(){
        return stream(STATUS.values())
                .map(s-> s.value)
                .collect(toList());
    }
}

You can use:

new ArrayList(STATUS.values()).stream().map(s -> s.getValue()).collect(Collectors.toList()) 
Related