Sorting an object in descending order using Array.sort and Lambda Expression

Shubhi :

I want to sort a collection of objects in descending order.

Below code is working to sort the itemDetails object in ascending order.

Arrays.sort(itemDetails, (a, b) -> 
    String.valueOf(a.getAvailableQuantity())
          .compareTo(String.valueOf(b.getAvailableQuantity())));

But I wanted the output in descending order.

user7294900 :

Switch to (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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=122494&siteId=1