5 java collections compiler-errors java-stream
我有这个方法:
public void fields(TableField... s){
// compilation error on next line
Collection<String> fields = Arrays.asList(s).stream().map(v -> v.getValue());
this.fields.addAll(fields);
}
Run Code Online (Sandbox Code Playgroud)
和TableField很简单只是看起来像:
class TableField {
public String getKey() {
return this.key;
}
public String getValue() {
return this.value;
}
}
Run Code Online (Sandbox Code Playgroud)
但我看到这个编译错误:
不兼容的类型.必需的集合,但'map'被推断为Stream:没有类型变量R的实例存在,以便Stream符合Collection
您需要collect那里的元素,因此将推断出类型:
Collection<String> fields = Arrays.stream(s) // Arrays.asList(s).stream()
.map(TableField::getValue) // map(v -> v.getValue())
.collect(Collectors.toList()); // or any other collection using 'Collectors.toCollection(<type>::new)'
Run Code Online (Sandbox Code Playgroud)