【问题标题】:Sorting a List of Pairs java [duplicate]排序对列表java [重复]
【发布时间】:2019-08-23 10:55:14
【问题描述】:

我列出了其中的对。我想先根据键对它们进行排序,如果键相同,则根据值进行排序。

我尝试了以下代码,但抛出异常不兼容类型:无法推断类型变量 T

 List<Pair<Integer,Integer>> list = new ArrayList<>();
 list.sort(Comparator.comparingInt(Pair::getKey).thenComparingInt(Pair::getValue);

错误:

不兼容的类型:无法推断类型变量 T (参数不匹配;无效的方法引用 类 Pair 中的方法 getKey 不能应用于给定类型 必需:无参数 找到:对象 原因:实际参数列表和形式参数列表的长度不同)

其中 T,K,V 是类型变量: T 扩展了在方法 comparisonInt(ToIntFunction) 中声明的 Object K 扩展类 Pair 中声明的 Object V 扩展类 Pair 中声明的 Object

【问题讨论】:

  • Pair 来自哪个库/包?
  • javafx.util.Pair
  • 附带说明,除非您真正开发 JavaFX 应用程序,否则您不应该使用该类型,因为您正在添加重要的依赖项。从 JDK 11 开始,默认情况下甚至不包含 JavaFX。
  • 我们可以逆序排列key,升序排列value吗?

标签: java java-8


【解决方案1】:

你需要帮助编译器为比较器推断出合适的类型:

list.sort(Comparator.<Pair<Integer, Integer>>comparingInt(Pair::getKey).thenComparingInt(Pair::getValue));

【讨论】:

  • 稍微简单的语法:list.sort(Comparator.comparingInt(Pair&lt;Integer,Integer&gt;::getKey) .thenComparingInt(Pair::getValue));
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-07
  • 1970-01-01
  • 2014-12-26
  • 2017-09-11
  • 1970-01-01
  • 2016-06-13
  • 1970-01-01
相关资源
最近更新 更多