我想转换一个 ArrayList<String>
至 Set<ScopeItem>
使用 Java 流。
ScopeItem is a enum;
items is an ArrayList<String>;
Set<ScopeItem> scopeItems = items.stream()
.map(scopeString -> ScopeItem.valueOf(scopeString))
.filter(Objects::nonNull)
.collect(Collectors.toSet());
对于不在枚举中的字符串,会抛出以下内容:
java.lang.IllegalArgumentException: No enum const...
理想情况下,我想跳过任何不匹配的字符串。
我想也许是使用平面图?有什么想法吗?
最佳答案
您可以将以下方法添加到您的 ScopeItem
:
public static ScopeItem valueOfOrNull(String name) {
try {
return valueOf(name);
} catch (IllegalArgumentException e) {
// no such element
return null;
}
}
并使用它来映射您的枚举值:
.map(scopeString -> ScopeItem.valueOfOrNull(scopeString))
后续 .filter()
非空值(您已经拥有)将过滤掉那些对应于非匹配字符串的空值。
关于java - 使用 Java 流将 ArrayList<String> 转换为 Set<ScopeItem>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48507878/