Get All Enum Values To A List

Simply_me :

I'm trying, and failing, to retrieve all Enum values and place them in a list using Java 8 and streams. So far I've tried the two approaches below, but neither one returns the value.

What am I doing wrong?

Code:

public class Main {
public static void main(String[] args) {
    List<String> fruits1 = Stream.of(FruitsEnum.values())
                                 .map(FruitsEnum::name)
                                 .collect(Collectors.toList());

    List<String> fruits2 = Stream.of(FruitsEnum.values().toString())
                                 .collect(Collectors.toList());

    // attempt 1
    System.out.println(fruits1);
    // attempt 2
    System.out.println(fruits2);
}

enum FruitsEnum {
    APPLE("APPL"),
    BANANA("BNN");

    private String fruit;

    FruitsEnum(String fruit) {this.fruit = fruit;}

    String getValue() { return fruit; }

   }
}

Output:

[APPLE, BANANA]
[[LMain$FruitsEnum;@41629346]

Desired:

["AAPL", "BNN"]
Naman :

You need to map with getValue

List<String> fruits = Stream.of(FruitsEnum.values())
                            .map(FruitsEnum::getValue) // map using 'getValue'
                            .collect(Collectors.toList());
System.out.println(fruits);

this will give you the output

[APPL, BNN]

Guess you like

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