我有一个自定义类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>
答案 0 :(得分:3)
这应该可以解决问题:
Set<Long> collectSet = customs.stream()
.flatMap(x -> x.getIds().stream())
.collect(Collectors.toSet());
您正在尝试将Set
转换为List
,这是不可能的。
答案 1 :(得分:2)
您可以按照以下步骤操作:
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>
时的预期返回类型)类型。