How to sort ArrayList <Long> in Java in descending order?
How to sort ArrayList in Java in descending order?
Here is one way for your list :
Collections.sort(list); Collections.reverse(list); Or you can implement your own Comparator to sort and eliminate the reverse step:
Collections.sort(list, new Comparator<Long>() { public int compare(Long o1, Long o2) { return o2.compareTo(o1); } }); Or even easier to use Collections.reverseOrder() , as you only change:
Collections.sort(list, Collections.reverseOrder()); Comparator<Long> comparator = Collections.reverseOrder(); Collections.sort(arrayList, comparator); You can use the following code below:
Collections.sort(list, Collections.reverseOrder()); or if you are going to use a custom comparator that you can use as indicated below
Collections.sort(list, Collections.reverseOrder(new CustomComparator()); Where CustomComparator is a comparator class that compares an object that is in the list.
Java 8
Good to do it in java 8 so much fun and easier
Collections.sort(variants,(a,b)->a.compareTo(b)); Collections.reverse(variants); Lambda expressions are rock here !!!
if you needed more than one logic to compare a and b , you could write this as
Collections.sort(variants,(a,b)->{ int result = a.compareTo(b); return result; }); Sort, then reverse.
A more general approach to implementing our own comparator below
Collections.sort(lst,new Comparator<Long>(){ public int compare(Long o1, Long o2) { return o2.compareTo(o1); } }); The following approach will sort the list in descending order, and also handle null values, just in case you have null values, then Collections.sort () will throw a NullPointerException
Collections.sort(list, new Comparator<Long>() { public int compare(Long o1, Long o2) { return o1==null?Integer.MAX_VALUE:o2==null?Integer.MIN_VALUE:o2.compareTo(o1); } }); Using Collections.sort() with a comparator that provides a descending order. See Javadoc for Collections.sort .
You can also sort ArrayList with TreeSet instead of comparator . Here is an example from the question I had previously for an integer array. I use "numbers" as a placeholder for an ArrayList .
import.java.util.*; class MyClass{ public static void main(String[] args){ Scanner input = new Scanner(System.in); ArrayList<Integer> numbers = new ArrayList<Integer>(); TreeSet<Integer> ts = new TreeSet<Integer>(numbers); numbers = new ArrayList<Integer>(ts); System.out.println("\nThe numbers in ascending order are:"); for(int i=0; i<numbers.size(); i++) System.out.print(numbers.get(i).intValue()+" "); System.out.println("\nThe numbers in descending order are:"); for(int i=numbers.size()-1; i>=0; i--) System.out.print(numbers.get(i).intValue()+" "); } }