![](/img/trans.png)
[英]Java error: incompatible types: no instance(s) of type variable(s) T exist so that Optional<T> conforms to Iterable<AvailableLicence>
[英]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
我正在尝试将ComplexItem
列表转换为它们对应的 ID Long
列表。 但是即使在使用(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() {
..............
}
没有理由期望 Collections2.transform 的Collections2.transform
是一个Collection
,会神奇地转换为一个Set
。 这就是标题中类型匹配错误的原因。 您需要将结果显式转换为集合或使用Collection
。
由于您已经在使用Guava
,因此您应该强烈考虑ImmutableSet
,所以它是
ImmutableSet<Long> ids
= ImmutableSet.copyOf(Collections2.transform(getComplexItems(), item -> item.id)));
退一步,记住 Guava 是在 Java Stream
之前创建的。 通常最好使用内置语言而不是第三方库,即使它和 Guava 一样好。 换句话说,更喜欢
getComplextItems().stream().map(item -> item.id).collect(toImmutableSet());
其中toImmutableSet()
是由ImmutableSet
定义的收集器。
你输入了错误的 Function
尝试这个
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.