Simon
Simon

Reputation: 965

Get values of enum as list of strings

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.

Upvotes: 2

Views: 5097

Answers (2)

kemalturgul
kemalturgul

Reputation: 55

Here is a Complete Code:

    public enum danger {

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

        private danger(String value) {
            this.value = value;
        }

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

        /**
         * @return the value
         */
        public String getValue() {
            return value;
        }
    }

List<String> dangerlist = Stream.of(danger.values())
                                .map(x -> x.getValue())
                                .collect(Collectors.toList());

Upvotes: 1

Mureinik
Mureinik

Reputation: 312219

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());

Upvotes: 3

Related Questions