如何对LinkedHashMap先按Value降序再按Key升序排序?
解决LinkedHashMap按Value降序、Key升序排序的问题
你的错误源于调用reversed()后,Java的类型推断机制无法明确Comparator的泛型类型,导致thenComparing方法无法匹配参数。以下是几种可行的解决方法:
方法1:显式指定泛型参数
通过在comparingByValue前添加<String, Integer>显式声明泛型,让编译器明确Comparator的类型:
playersSkillsPoints.get(user).entrySet().stream() .sorted(Map.Entry.<String, Integer>comparingByValue().reversed() .thenComparing(Map.Entry.comparingByKey())) .forEach(e -> System.out.printf("- %s <::> %d%n", e.getKey(), e.getValue()));
方法2:使用Comparator.comparing构建复合排序规则
这种写法更直观,直接指定Value的逆序比较,再链式添加Key的升序比较:
playersSkillsPoints.get(user).entrySet().stream() .sorted(Comparator.comparing(Map.Entry<String, Integer>::getValue, Comparator.reverseOrder()) .thenComparing(Map.Entry::getKey)) .forEach(e -> System.out.printf("- %s <::> %d%n", e.getKey(), e.getValue()));
方法3:单独定义Comparator(可读性更佳)
如果排序逻辑需要复用,可提前定义Comparator变量,代码结构更清晰:
// 先按Value降序,再按Key升序的比较器 Comparator<Map.Entry<String, Integer>> skillComparator = Comparator.comparing(Map.Entry::getValue, Comparator.reverseOrder()) .thenComparing(Map.Entry::getKey); playersSkillsPoints.get(user).entrySet().stream() .sorted(skillComparator) .forEach(e -> System.out.printf("- %s <::> %d%n", e.getKey(), e.getValue()));
补充说明
原代码中comparingByValue().reversed()返回的Comparator泛型被隐式处理,编译器无法识别它是针对Map.Entry<String, Integer>的比较器,因此调用thenComparing时会出现方法解析错误。显式指定泛型或使用Comparator.comparing的重载方法(传入比较器参数),都能解决这个类型推断问题。
内容的提问来源于stack exchange,提问作者Nataliikaa PetroOwwa
相关产品推荐
相关产品推荐

