我有一个自定义类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());
现在我将第2行和第3行合并为一行,如下所示。
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>
类型的变量时所期望的返回类型。
这应该可以做到:
Set<Long> collectSet = customs.stream()
.flatMap(x -> x.getIds().stream())
.collect(Collectors.toSet());
您正在尝试将Set
转换为List
,这是不可能的。