gpt4 book ai didi

java - 对列表对进行排序 java

转载 作者:行者123 更新时间:2023-12-01 16:43:34 28 4
gpt4 key购买 nike

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

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

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

错误:

incompatible types: cannot infer type-variable(s) T (argument mismatch; invalid method reference method getKey in class Pair cannot be applied to given types required: no arguments found: Object reason: actual and formal argument lists differ in length)

where T,K,V are type-variables: T extends Object declared in method comparingInt(ToIntFunction) K extends Object declared in class Pair V extends Object declared in class Pair

最佳答案

您需要帮助编译器推断比较器的适当类型:

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

关于java - 对列表对进行排序 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57624889/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com