Java8 Lambda 表达式,用于迭代枚举值并初始化最终成员
我有一个像这样的静态枚举:
private static enum standardAttributes {
id, gender, firstname, lastname, mail, mobile
}
我需要所有值作为字符串。因此,我有一个这样的方法:
public static List<String> getStandardRecipientsAttributes() {
List<String> standardAttributesList = new ArrayList<String>();
for (standardAttributes s : standardAttributes.values())
standardAttributesList.add(s.toString());
return standardAttributesList;
}
无需在每次调用此方法时都创建相同的 List。所以我创建了一个静态成员:
static final List<String> standardAttributesList;
static {
standardAttributesList = getStandardRecipientsAttributes();
}
这一切都很好,但我想知道是否有一个花哨的Lambda表达式来替换该方法。像这样:
Arrays.asList(standardAttributes.values()).forEach((attribute) -> standardAttributesList.add(attribute.toString()));
两个问题:
- 我可以避免使用 Arrays.asList 包装器吗?
- 如何处理编译器错误:空白的最终字段 standardAttributesList 可能尚未初始化?