java Java8 Lambda 表达式迭代枚举值并初始化最终成员
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29251967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java8 Lambda expression to iterate over enum values and initialize final member
提问by s.meissner
I have a static enum like this:
我有一个像这样的静态枚举:
private static enum standardAttributes {
id, gender, firstname, lastname, mail, mobile
}
I need all the values as String. Therefore I have a method like this:
我需要所有值作为字符串。因此我有一个这样的方法:
public static List<String> getStandardRecipientsAttributes() {
List<String> standardAttributesList = new ArrayList<String>();
for (standardAttributes s : standardAttributes.values())
standardAttributesList.add(s.toString());
return standardAttributesList;
}
There is no need to create the same List everytime this method is called. So I created a static member:
每次调用此方法时无需创建相同的 List。所以我创建了一个静态成员:
static final List<String> standardAttributesList;
static {
standardAttributesList = getStandardRecipientsAttributes();
}
This is all fine, but I wonder if there is a fancy Lambda expression to replace the method. Something like this:
这一切都很好,但我想知道是否有一个花哨的 Lambda 表达式来替换该方法。像这样的东西:
Arrays.asList(standardAttributes.values()).forEach((attribute) -> standardAttributesList.add(attribute.toString()));
Two questions:
两个问题:
- Can I avoid the Arrays.asList wrapper?
- How can I handle the compiler error: The blank final field standardAttributesList may not have been initialized?
- 我可以避免 Arrays.asList 包装器吗?
- 我该如何处理编译器错误:空白的最终字段 standardAttributesList 可能尚未初始化?
回答by Peter Lawrey
You can do
你可以做
static final List<String> standardAttributesList =
Stream.of(values())
.map(Enum::name)
.collect(Collectors.toList());
This will create a Stream from an the array of values, apply the .name()
method to each one and finally collect all the results into a List.
这将从值数组创建一个流,将.name()
方法应用于每个值,最后将所有结果收集到一个列表中。