2

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.

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

I would recommend against doing something as subtle as flipping the parameter order: it looks like a typo, TBH. If you're going to do something like this, I would reverse the order you use the arguments inside the lambda body.
@AndyTurner added comment Actually change names to meaningful so sorting logic will be understandable
2

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

3 Comments

thanks but this is not working in my case giving me a error of typecasting of object.
@Shubhi Add the type of the array element to the lambda parameter, e.g. (ItemDetail a) -> . Demo
I added it but that is giving me runtime error. @ Andy Turner
1

Add a minus:

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

4 Comments

What if compareTo had returned Integer.MIN_VALUE?
@AndyTurner it will not. But if that's a concern for you, you can also swap a and b.
It might not in this specific case, so you can use this "one weird trick" here, but it should come with a health warning that you shouldn't do it in the general case.
@AndyTurner fair enough

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.