Get values of enum as list of strings

Simon :

I have the following enum and want to convert it to a list of its string values:

@Getter
@AllArgsConstructor
public enum danger{

    Danger("DGR"),
    Normal("NOR");


    /**
     * The value.
     */
    private final String value;
}

Desired Output: List of "DGR" and "NOR"

My current solution looks like:

List<String> dangerlist = Stream.of(DangerousShipment.values())
                .map(Enum::name)
                .collect(Collectors.toList());

The problem is, I can only select the name of the enum and not the actual value.

Mureinik :

Add a getter for the value:

public enum DangerShipment {
    // Code from the OP omitted for brevity

    public String getValue() {
        return value;
    }
}

And use it when constructing the list:

List<String> dangerlist = Stream.of(DangerousShipment.values())
                                .map(DangerousShipment::getValue)
                                .collect(Collectors.toList());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=130603&siteId=1