【问题标题】: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不兼容的类型:不存在类型变量 F、T 的实例,因此 java.util.Collection<T> 符合 java.util.Set<java.lang.Long
【发布时间】:2021-05-23 17:28:24
【问题描述】:

我正在尝试将ComplexItem 的列表转换为它们对应的 ID 列表Long。但是即使在使用(Collection&lt;ComplexItem&gt;)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() {
        ..............
 }

【问题讨论】:

  • 为什么不干脆做getComplexItems().stream().map(item -&gt; item.id).collect(Collectors::toSet)
  • @QBrute 应该可以工作,但想知道上面的代码有什么问题

标签: java collections transform


【解决方案1】:

没有理由期望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 Streams 之前创建的。通常最好使用内置语言而不是第三方库,即使它和 Guava 一样好。换句话说,更喜欢

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

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

【讨论】:

    【解决方案2】:

    你的函数导入错误

    试试这个

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

    【讨论】:

      猜你喜欢
      • 2017-04-22
      • 2019-12-16
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 2022-10-18
      • 2019-11-08
      • 2017-12-04
      相关资源
      最近更新 更多