簡體   English   中英

不兼容的類型:不存在類型變量 F、T 的實例,因此 java.util.Collection<t> 符合 java.util.Set <java.lang.long< div><div id="text_translate"><p> 我正在嘗試將ComplexItem列表轉換為它們對應的 ID Long列表。 但是即使在使用(Collection&lt;ComplexItem&gt;)對getCollection()調用進行類型轉換后,也不會出現上述錯誤 go</p><pre> Set&lt;Long&gt; ids = Collections2.transform( getComplexItems(), new Function&lt;ComplexItem, Long&gt;() { @Override public Long apply(final ComplexItem item) { return item.id; } })); public List&lt;ComplexItem&gt; getComplexItems() {.............. }</pre> </div></java.lang.long<></t>

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM