How to sort ArrayList<Long> in decreasing order?

Java

Java Problem Overview


How to sort an ArrayList<Long> in Java in decreasing order?

Java Solutions


Solution 1 - Java

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());

Solution 2 - Java

Comparator<Long> comparator = Collections.reverseOrder();
Collections.sort(arrayList, comparator);

Solution 3 - Java

You can use the following code which is given below;

Collections.sort(list, Collections.reverseOrder());

or if you are going to use custom comparator you can use as it is given below

Collections.sort(list, Collections.reverseOrder(new CustomComparator());

Where CustomComparator is a comparator class that compares the object which is present in the list.

Solution 4 - Java

Java 8

well doing this in java 8 is so much fun and easier

Collections.sort(variants,(a,b)->a.compareTo(b));
Collections.reverse(variants);

Lambda expressions rock here!!!

in case you needed a more than one line logic for comparing a and b you could write it like this

Collections.sort(variants,(a,b)->{
    int result = a.compareTo(b);
    return result;
});

Solution 5 - Java

Sort normally and use Collections.reverse();

Solution 6 - Java

For lamdas where your long value is somewhere in an object I recommend using:

.sorted((o1, o2) -> Long.compare(o1.getLong(), o2.getLong()))

or even better:

.sorted(Comparator.comparingLong(MyObject::getLong))

Solution 7 - Java

Sort, then reverse.

Solution 8 - Java

By using Collections.sort() with a comparator that provides the decreasing order. See Javadoc for Collections.sort.

Solution 9 - Java

A more general approach to implement our own Comparator as below

Collections.sort(lst,new Comparator<Long>(){
                public int compare(Long o1, Long o2) {
                    return o2.compareTo(o1);
                }
            });

Solution 10 - Java

The following approach will sort the list in descending order and also handles the 'null' values, just in case if you have any null values then Collections.sort() will throw 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);

		}
	});

Solution 11 - Java

You can also sort an ArrayList with a TreeSet instead of a comparator. Here's an example from a question I had before for an integer array. I'm using "numbers" as a placeholder name for the 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()+" ");
    }
}

Solution 12 - Java

So, There is something I would like to bring up which I think is important and I think that you should consider. runtime and memory. Say you have a list and want to sort it, well you can, there is a built in sort or you could develop your own. Then you say, want to reverse the list. That is the answer which is listed above.

If you are creating that list though, it might be good to use a different datastructure to store it and then just dump it into an array.

Heaps do just this. You filter in data, and it will handle everything, then you can pop everything off of the object and it would be sorted.

Another option would be to understand how maps work. A lot of times, a Map or HashMap as something things are called, have an underlying concept behind it.

For example.... you feed in a bunch of key-value pairs where the key is the long, and when you add all the elements, you can do: .keys and it would return to you a sorted list automatically.

It depends on how you process the data prior as to how i think you should continue with your sorting and subsequent reverses

Solution 13 - Java

Comparator's comparing method can be used to compare the objects and then method reversed() can be applied to reverse the order -

list.stream().sorted(Comparator.comparing(Employee::getName).reversed()).collect(toList());

Solution 14 - Java

Using List.sort() and Comparator.comparingLong()

numberList.sort(Comparator.comparingLong(x -> -x));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTamaraView Question on Stackoverflow
Solution 1 - JavaWhiteFang34View Answer on Stackoverflow
Solution 2 - JavaUmesh KView Answer on Stackoverflow
Solution 3 - JavaBalasubramanian JayaramanView Answer on Stackoverflow
Solution 4 - JavaazerafatiView Answer on Stackoverflow
Solution 5 - JavaManojView Answer on Stackoverflow
Solution 6 - JavaTigerwareView Answer on Stackoverflow
Solution 7 - Javauser541686View Answer on Stackoverflow
Solution 8 - JavaHeiko RuppView Answer on Stackoverflow
Solution 9 - Javajosephj1989View Answer on Stackoverflow
Solution 10 - JavaJagadeeshView Answer on Stackoverflow
Solution 11 - Java009View Answer on Stackoverflow
Solution 12 - JavaFallenreaperView Answer on Stackoverflow
Solution 13 - JavaAmrendraView Answer on Stackoverflow
Solution 14 - JavadeadshotView Answer on Stackoverflow