[英]incompatible types: no instance(s) of type variable(s) F,T exist so that java.util.Collection<T> conforms to java.util.Set<java.lang.Long
I am trying to convert the list of ComplexItem
to a list of their corresponding IDs Long
.我正在尝试将
ComplexItem
列表转换为它们对应的 ID Long
列表。 But getting the above error which doesn't go even after typecasting the getCollection()
call with (Collection<ComplexItem>)
但是即使在使用
(Collection<ComplexItem>)
对getCollection()
调用进行类型转换后,也不会出现上述错误 go
Set<Long> ids = Collections2.transform(
getComplexItems(), new Function<ComplexItem, Long>() {
@Override public Long apply(final ComplexItem item) {
return item.id;
}
}));
public List<ComplexItem> getComplexItems() {
..............
}
There's no reason to expect that the result of Collections2.transform
, which is a Collection
, will be magically transformed to a Set
.没有理由期望 Collections2.transform 的
Collections2.transform
是一个Collection
,会神奇地转换为一个Set
。 This is the reason for the type matching error in the title.这就是标题中类型匹配错误的原因。 You'll need either to convert the result to a set explicitly or make do with the
Collection
.您需要将结果显式转换为集合或使用
Collection
。
Since you're already using Guava
, you should strongly consider ImmutableSet
, so it's由于您已经在使用
Guava
,因此您应该强烈考虑ImmutableSet
,所以它是
ImmutableSet<Long> ids
= ImmutableSet.copyOf(Collections2.transform(getComplexItems(), item -> item.id)));
Taking a step back, remember Guava was created before Java Stream
s.退一步,记住 Guava 是在 Java
Stream
之前创建的。 It's generally preferable to use language built-ins rather than a third party library, even when it's as good as Guava.通常最好使用内置语言而不是第三方库,即使它和 Guava 一样好。 In other words, prefer
换句话说,更喜欢
getComplextItems().stream().map(item -> item.id).collect(toImmutableSet());
where toImmutableSet()
is a collector defined by ImmutableSet
.其中
toImmutableSet()
是由ImmutableSet
定义的收集器。
you got in the wrong import for Function你输入了错误的 Function
try this尝试这个
Collection<Long> ids = Collections2.transform(
getComplexItems(), new com.google.common.base.Function<ComplexItem, Long>() {
@Override public Long apply(final ComplexItem item) {
return item.id;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.