使用 Java8 流实现此集合的最佳方式
Best way to use Java8 streams to implement this collection
private enum EnumVals {
FIRST(new String[]{"a","b"}),
SECOND(new String[]{"a","b","c","d"}),
THIRD(new String[]{"d","e"});
private String[] vals;
EnumVals(String[] q) {
vals=q;
}
public String[] getValues(){
return vals;
}
};
我需要的是所有EnumVals.getValues()的唯一组合列表。
String[] allVals = {"a","b","c","d","e"}
我做了类似下面的事情,但它抛出了错误:
Stream.of(EnumVals.values()).map(w->w.getValues()).collect(Collectors.toCollection(HashSet::new)).toArray(new String[0]);
您需要在流中使用 flatMap
to flatten the arrays. Additionally, you can use distinct()
,而不是收集到 HashSet
。
Arrays.stream(EnumVals.values())
.map(EnumVals::getValues)
.flatMap(Arrays::stream)
.distinct()
.toArray(String[]::new);
private enum EnumVals {
FIRST(new String[]{"a","b"}),
SECOND(new String[]{"a","b","c","d"}),
THIRD(new String[]{"d","e"});
private String[] vals;
EnumVals(String[] q) {
vals=q;
}
public String[] getValues(){
return vals;
}
};
我需要的是所有EnumVals.getValues()的唯一组合列表。
String[] allVals = {"a","b","c","d","e"}
我做了类似下面的事情,但它抛出了错误:
Stream.of(EnumVals.values()).map(w->w.getValues()).collect(Collectors.toCollection(HashSet::new)).toArray(new String[0]);
您需要在流中使用 flatMap
to flatten the arrays. Additionally, you can use distinct()
,而不是收集到 HashSet
。
Arrays.stream(EnumVals.values())
.map(EnumVals::getValues)
.flatMap(Arrays::stream)
.distinct()
.toArray(String[]::new);