You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Comparator thenComparing()方法报错:不存在符合条件的类型变量U实例

问题:Comparator.thenComparing() 泛型类型不匹配报错

报错信息

no instance(s) of type variable(s) U exist so 
that Object conforms to Comparable<? super U>

报错代码

Map<Integer, Long> sortedCards = new LinkedHashMap<>();
List<Card> cards = // initializing the list

cards.stream().collect(
    Collectors.groupingBy(
        card -> card.kind.rank,
        Collectors.counting()
    ))
    .entrySet().stream()
    .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())
                     .thenComparing(Map.Entry::getKey))
    .forEachOrdered(e -> sortedCards.put(e.getKey(), e.getValue()));

相关类定义

Card类:

public static class Card implements Comparable<Card> {

    private Kind kind;
    
    // constructors, getters, etc.
}

Kind枚举:

public enum Kind {

    TWO(1, "2"), THREE(2, "3"), FOUR(3, "4"), // etc.;
    
    public int rank;
    // constructors, getters, etc.
}

报错原因

问题出在Map.Entry.comparingByValue(Comparator.reverseOrder())的类型推断上:

  • 当comparingByValue传入自定义Comparator(这里是Comparator.reverseOrder())时,它的返回类型是Comparator<Map.Entry<?, Long>>,Key的类型被通配符?模糊处理。
  • 后续调用thenComparing(Map.Entry::getKey)时,编译器无法确认通配符?对应的Key类型(Integer)是否实现了Comparable接口,导致泛型类型匹配失败,抛出错误。

正确用法与修复方案

有两种简洁的修复方式:

方式一:显式指定泛型类型

在comparingByValue前显式声明Entry的Key和Value类型,让编译器明确类型信息:

.sorted(Map.Entry.<Integer, Long>comparingByValue(Comparator.reverseOrder())
                 .thenComparing(Map.Entry::getKey))

方式二:用Comparator.comparing替代Map.entry的方法

通过Comparator.comparing直接指定Value的比较规则,上下文可以自动推断Key的类型:

.sorted(Comparator.comparing(Map.Entry<Integer, Long>::getValue, Comparator.reverseOrder())
                 .thenComparing(Map.Entry::getKey))

修复后的完整代码

Map<Integer, Long> sortedCards = new LinkedHashMap<>();
List<Card> cards = // initializing the list

cards.stream().collect(
    Collectors.groupingBy(
        card -> card.kind.rank,
        Collectors.counting()
    ))
    .entrySet().stream()
    .sorted(Map.Entry.<Integer, Long>comparingByValue(Comparator.reverseOrder())
                     .thenComparing(Map.Entry::getKey))
    .forEachOrdered(e -> sortedCards.put(e.getKey(), e.getValue()));

内容的提问来源于stack exchange,提问作者Magda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 13:11:37