【问题标题】:java: incompatible types: inference variable RR has incompatible boundsjava:不兼容的类型:推理变量 RR 具有不兼容的界限
【发布时间】:2021-11-02 11:42:22
【问题描述】:

jdk 1.8

设置和收集。

我想获得 > 0 的交叉点数。

我试试这个:

SortedSet<VsatVlan> vsatVlans;
Collection<Integer> mobilityNsVlansList = mobilityNS.getVlanIds();
....
long intersectionCount = vsatVlans.stream()
    .filter(vsatVlan -> mobilityNsVlansList.contains(vsatVlan.getVlanId()))
    .collect(Collectors.collectingAndThen(
        Collectors.toSet(),
        set -> { // error here
            if (set.size() != 1) {
                throw new IllegalStateException();
            }
            return set.size();
        }
    ));

但我得到错误:

incompatible parameter types in lambda expression: expected Set<Object> but found Set<VsatVlan>

java: incompatible types: inference variable RR has incompatible bounds
lower bounds: java.lang.Long,java.lang.Object
lower bounds: java.lang.Integer

【问题讨论】:

  • 你想达到什么目的?计算集合有多少个元素,列表中出现了哪些元素?如果是,为什么是 collectingAndThenstream().filter(...).count() 不应该足够吗?
  • intersectionCount 设为int。这似乎把整个类型推断都扔掉了。
  • @Eritrean 我需要像“stream().filter(...).count() > 0”这样的 smt。有可能吗?
  • @a_subscriber 但那将是一个不长的布尔值。
  • 这是一种方法吗?它返回什么?您是否尝试返回交集计数,如果计数为 0,则抛出异常?

标签: java java-stream


【解决方案1】:

如果我做对了,您只想在不为零的情况下返回交集计数,否则您想抛出异常。您需要明确提供集合的类型以消除您得到的错误:

return vsatVlans.stream()
                .filter(vsatVlan -> mobilityNsVlansList.contains(vsatVlan.getVlanId()))
                .collect(Collectors.collectingAndThen(Collectors.toSet(),
                    (Set<VsatVlan> set) -> {
                        if (set.size() == 0) {
                            throw new IllegalStateException("");
                        }
                        return set.size();
                    }
               ));

你也可以在这里使用 Optionals 并避免 if 块:

return vsatVlans.stream()
               .filter(vsatVlan -> mobilityNsVlansList.contains(vsatVlan.getVlanId()))
               .collect(Collectors.collectingAndThen(Collectors.counting(), Optional::of))
               .filter(x -> x > 0)
               .orElseThrow(() -> new IllegalStateException(""));

但 IMO 计数然后签入单独的 if 块,比上述两个更具可读性:

long count = vsatVlans.stream()
                      .filter(vsatVlan -> mobilityNsVlansList.contains(vsatVlan.getVlanId()))
                      .count();
if(count == 0){
    new IllegalStateException("")
}
return count;

【讨论】:

  • 在我看来,OP 想要distinct().count()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多