2 回答
![?](http://img1.sycdn.imooc.com/54584d1300016b9b02200220-100-100.jpg)
TA贡献1900条经验 获得超5个赞
Optional.ofNullable(list).map(List::stream)会给您一个Optional<Stream<String>>,您无法调用filter。
您可以将整个Stream处理放入Optional的中map():
public Builder withColors(List<String> colors) {
this.colors = Optional.ofNullable(colors).map(
list -> list.stream()
.filter(Objects::nonNull)
.map(color-> Color.valueOf(color))
.collect(Collectors.toList()))
.orElse(null);
return this;
}
![?](http://img1.sycdn.imooc.com/54584cde0001d19202200220-100-100.jpg)
TA贡献1811条经验 获得超5个赞
您可能需要重新考虑几件事。
首先可能要传递aSet<String> colors而不是aList会更有意义,因为似乎这Color是一个枚举。然后,可能会更有意义核对equalsIgnoreCase,这样red或RED会仍然产生一个枚举实例。另外if statement,检查可能为空的输入可能更清晰。以及最后一个相反方向的流-从这enum将更有意义(还避免了空检查),我只是为了简单起见没有实施上述建议。
public Builder withColors(List<String> colors) {
if(colors == null){
this.colors = Collection.emptyList();
}
this.colors = EnumSet.allOf(Color.class)
.stream()
.filter(x -> colors.stream().anyMatch(y -> x.toString().equals(y)))
.collect(Collectors.toList());
return this;
}
添加回答
举报