How to sort an ArrayList<Long>
in Java in decreasing order?
Create an ArrayList. Sort the contents of the ArrayList using the sort() method of the Collections class. Then, reverse array list using the reverse() method of the Collections class.
Sort in Descending order The sort() method accepts a reverse parameter as an optional argument. Setting reverse = True sorts the list in the descending order. Alternatively for sorted() , you can use the following code.
To sort long array in Java, use the Arrays. sort() method. Let's say the following is our long array. long[] arr = new long[] { 987, 76, 5646, 96,8768, 8767 };
Here's one way for your list
:
list.sort(null); Collections.reverse(list);
Or you could implement your own Comparator
to sort on and eliminate the reverse step:
list.sort((o1, o2) -> o2.compareTo(o1));
Or even more simply use Collections.reverseOrder()
since you're only reversing:
list.sort(Collections.reverseOrder());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With