![](/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.