Get String of concatenated Enum long values using Java Stream

Viewed 68

I have an Enum with int values:

public enum Enum{
    ONE(1) ,
    TWO(2) ,
    THREE(3),
    FOUR(4) ;

    private final long id;

    Enum(final long id) {
        this.id = id;
    }

    @Override
    public long getId() {
        return this.id;
    }
}

I am trying to print the ids of all enum in a string using java stream. Something like this:

String ids = Stream.of(Enum.values())
                   .map(value -> value.getId())
                   .collect(Collectors.joining(",");

I tried mapToObj and boxed but my IDE doesn't recognize it. Please help

2 Answers

You should map to a String before collecting to a String:

String ids = Stream.of(Enum.values())
        .map(value -> String.valueOf(value.getId()))
        .collect(Collectors.joining(","));

Output:

1,2,3,4

You could add a method in Enum to return the string value of your id.

public String getIdValue() {
    return String.valueOf(this.id);
}

Collectors.joining expects a stream of String, but you are currently passing a stream of long.

return Stream.of(Enum.values())
             .map(Enum::getIdValue)
             .collect(Collectors.joining(",");
Related