Java comparator.Comparating(o->;x).reversed不起作用

Java comparator.Comparating(o->;x).reversed不起作用,java,arrays,list,collections,comparator,Java,Arrays,List,Collections,Comparator,我有一个实现comparable的类Country,并定义了comparTo方法 我正在尝试对国家项目的集合(ArrayList)进行排序 Collections.sort(Mylist,Comparator.comparing(Country::getCountryName)) // Works Collections.sort(Mylist, Comparator.comparing(Country::getCountryName).reversed()) // Works Collecti

我有一个实现comparable的类Country,并定义了comparTo方法

我正在尝试对国家项目的集合(ArrayList)进行排序

Collections.sort(Mylist,Comparator.comparing(Country::getCountryName)) // Works
Collections.sort(Mylist, Comparator.comparing(Country::getCountryName).reversed()) // Works
Collections.sort(Mylist, Comparator.comparing(o-> o.getCountryName())) //Works
Collections.sort(Mylist, Comparator.comparing((o-> o.getCountryName())).reversed()) //Does not works
我不明白为什么最后一个不起作用,我的IDE告诉我,一旦我添加了.reversed()并拒绝调用getCountryName()方法,o就是对象类型

但是,它被正确地检测为国家/地区类型,没有.reversed()

我不知道为什么。特别是在::符号起作用的情况下

Collections.sort(listePays, Comparator.comparing((Country o) -> o.getCountryName()).reversed())
是支持者语法。更多解释请参见Thomas评论


什么是比较器的反向?@NirAlfasi这只是一个比较器反转结果,也就是做一个反向顺序。在OP的例子中,它应该按降序名称对国家进行排序。我不得不在这里猜测,因为我目前缺乏正确思考的能力;)但我要说的是,在后一种情况下,类型推断无法正常工作,因为lambda没有提供类型作为情况1和2中的函数引用,也不能从“赋值”中推断出来(如情况3中,参数类型为
Country
),因为还没有赋值。在这里帮助编译器是可能的:
比较((国家o)->o.getCountryName()).reversed()
应该像
比较(o->o.getCountryName()).reversed())
一样工作。哇。我要深入研究一下语法。我甚至不确定我是否理解它,但它是有效的。谢谢。还有
Collections.reverseOrder(Comparator.comparating(o->o.getCountryName())
Comparator.comparating(o->o.getCountryName(),Comparator.reverseOrder())
就可以了。顺便说一句,您不再需要转到实用程序方法
Collections.sort(…)
。现在,您可以直接在列表上调用
sort
,例如
mylist.sort(comparator)
Collections.sort(Mylist, Comparator.<Country, String>comparing(o ->o.getCountryName()).reversed())
Collections.sort(Mylist,Collections.reverseOrder(Comparator.comparing(o -> o.getCountryName())))
Collections.sort(listePays,Comparator.comparing(o -> o.getCountryName(), Comparator.reverseOrder()))