Simply_me
Simply_me

Reputation: 2970

Get All Enum Values To A List

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"]

Upvotes: 16

Views: 12275

Answers (3)

Hadi
Hadi

Reputation: 17289

Using of EnumSet is other way:

 List<String> fruits = EnumSet.allOf(FruitsEnum.class)
     .stream()
     .map(FruitsEnum::getValue)
     .collect(Collectors.toList());

Upvotes: 2

Naman
Naman

Reputation: 31868

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]

Upvotes: 13

ETO
ETO

Reputation: 7269

This should do the trick:

Arrays.stream(FruitsEnum.values())
      .map(FruitsEnum::getValue)
      .collect(Collectors.toList());

Upvotes: 6

Related Questions