不兼容类型:不存在类型变量 F、T 的实例,因此 java.util.Collection<T> 符合 java.util.Set<java.lang.Long

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() 调用进行类型转换后也不会出现
Set<Long> ids = Collections2.transform(
                    getComplexItems(), new Function<ComplexItem, Long>() {
                        @Override public Long apply(final ComplexItem item) {
                            return item.id;
                        }
                    }));

 public List<ComplexItem> getComplexItems() {
        ..............
 }

你导入错误的函数

试试这个

    Collection<Long> ids = Collections2.transform(
        getComplexItems(), new com.google.common.base.Function<ComplexItem, Long>() {
            @Override public Long apply(final ComplexItem item) {
                return item.id;
            }
        });

没有理由期望 result of Collections2.transform, which is a Collection 会神奇地变成 Set。这就是标题中类型匹配错误的原因。您需要将结果显式转换为一个集合,或者使用 Collection.

既然你已经在使用Guava,你应该强烈考虑ImmutableSet,所以它是

ImmutableSet<Long> ids 
    = ImmutableSet.copyOf(Collections2.transform(getComplexItems(), item -> item.id)));

退一步说,Guava 是在 Java Stream 之前创建的。通常最好使用语言 built-ins 而不是第三方库,即使它和 Guava 一样好。也就是说,prefer

getComplextItems().stream().map(item -> item.id).collect(toImmutableSet());

其中 toImmutableSet() 是由 ImmutableSet 定义的收集器。