[英]Sorting an object in descending order using Array.sort and Lambda Expression
I want to sort a collection of objects in descending order. 我想按降序对对象集合进行排序。
Below code is working to sort the itemDetails object in ascending order. 下面的代码用于按升序对itemDetails对象进行排序。
Arrays.sort(itemDetails, (a, b) ->
String.valueOf(a.getAvailableQuantity())
.compareTo(String.valueOf(b.getAvailableQuantity())));
But I wanted the output in descending order. 但是我希望输出按降序排列。
Switch to (b, a)
: 切换至(b, a)
:
Arrays.sort(itemDetails, (b, a) ->
String.valueOf(a.getAvailableQuantity())
.compareTo(String.valueOf(b.getAvailableQuantity())));
Actually change names to meaningful so sorting logic will be understandable 实际上将名称更改为有意义的名称,以便可以理解排序逻辑
Use Comparator.comparing
(to avoid having to repeat the String.valueOf
and getAvailableQuantity
) and Comparator.reversed()
(to clearly convey the fact that you are reversing the sort order): 使用Comparator.comparing
(避免重复String.valueOf
和getAvailableQuantity
)和Comparator.reversed()
(以清楚地表明您正在反转排序顺序):
Arrays.sort(
itemDetails,
Comparator.comparing((ItemDetails a) -> String.valueOf(a.getAvailableQuantity())).reversed());
where ItemDetails
is the name of the element type of the array (or some supertype which also has the getAvailableQuantity
method). 其中ItemDetails
是数组的元素类型的名称(或某些具有getAvailableQuantity
方法的超类型)。
加减号:
Arrays.sort(itemDetails, (a, b) -> -String.valueOf(a.getAvailableQuantity()).compareTo(String.valueOf(b.getAvailableQuantity())));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.