Get All Enum Values To A List

  • A+
Category:Languages

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

 


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] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: