我有一个自定义类 Custom
.
public class Custom {
private Long id;
List<Long> ids;
// getters and setters
}
现在我有 List<Custom>
对象。我想转换 List<Custom>
进入List<Long>
.
我编写了如下代码,它运行良好。
List<Custom> customs = Collections.emptyList();
Stream<Long> streamL = customs.stream().flatMap(x -> x.getIds().stream());
List<Long> customIds2 = streamL.collect(Collectors.toList());
Set<Long> customIds3 = streamL.collect(Collectors.toSet());
现在我将 line2 和 line3 组合成一行,如下所示。
List<Long> customIds = customs.stream().flatMap(x -> x.getIds().stream()).collect(Collectors.toSet());
现在,这段代码没有编译,我遇到了错误 -
error: incompatible types: inference variable R has incompatible bounds
List<Long> customIds = customs.stream().flatMap(x -> x.getIds().stream()).collect(Collectors.toSet());
^
equality constraints: Set<Long>
upper bounds: List<Long>,Object
where R,A,T are type-variables:
R extends Object declared in method <R,A>collect(Collector<? super T,A,R>)
A extends Object declared in method <R,A>collect(Collector<? super T,A,R>)
T extends Object declared in interface Stream
如何转换 List<Custom>
进入Set<Long>
或 List<Long>
正确
最佳答案
你可以这样做:
List<Custom> customs = Collections.emptyList();
Set<Long> customIdSet = customs.stream()
.flatMap(x -> x.getIds().stream())
.collect(Collectors.toSet()); // toSet and not toList
你得到编译器错误的原因是你使用了不正确的 Collector
它返回一个 List 而不是 Set ,这是您将其分配给 Set<Long>
的变量时预期的返回类型类型。
关于java - "error: incompatible types: inference variable R has incompatible bounds"单行flatMap流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53014676/