繁体   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