获取所有枚举值并将其添加到列表中

16

我正尝试使用Java 8和流将所有枚举值检索并放入列表中,但尝试了下面两种方法都没有返回值。

我做错了什么?

代码:

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; }

   }
}

输出:

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

期望的:

["AAPL", "BNN"]

@Aomine,这不是重复问题,因为那个问题中标记的解决方案在这里不起作用。实际上,我已经将它合并到我的片段(fruits1)中了。 - Simply_me
如果您能更具体地说明您当前的结果以及您期望得到的结果,我会考虑重新开放。 - Ousmane D.
1
你期望 FruitsEnum.values().toString() 做什么?实际上它会将值的数组转换为字符串,而不是像你期望的那样转换为字符串的数组。 - ETO
2
我添加了所需的输出;是的 @ETO 很好的观点。 - Simply_me
4
使用 Stream.of(FruitsEnum.values()).map(FruitsEnum::getValue).collect(Collectors.toList()); - Amit
显示剩余8条评论
3个回答

13

你需要使用 getValue 进行 map

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

这将给你输出结果

[APPL, BNN]

6
这个方法应该可以解决问题:
Arrays.stream(FruitsEnum.values())
      .map(FruitsEnum::getValue)
      .collect(Collectors.toList());

2

使用EnumSet是另一种方法:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接