Shubhi
Shubhi

Reputation: 41

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.

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

But I wanted the output in descending order.

Upvotes: 2

Views: 121

Answers (3)

Andy Turner
Andy Turner

Reputation: 140318

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):

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).

Upvotes: 2

Ori Marko
Ori Marko

Reputation: 58772

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

Upvotes: 2

Maurice Perry
Maurice Perry

Reputation: 9650

Add a minus:

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

Upvotes: 1

Related Questions