How to Sort Arraylist Elements in Descending Order in Java


The example aims to demonstrate how to sort elements of ArrayList in a descending order by comparator and reverseOrder method in Java.

Source Code

1)

package com.beginner.examples;

import java.util.ArrayList;
import java.util.Collections;

public class SortOfArrayListExample {

	
	public static void main(String[] args) {
		
		ArrayList numList = new ArrayList();
		
		numList.add(1);
		numList.add(4);
		numList.add(7);
		numList.add(5);
		numList.add(2);
		
		//Objects in an ArrayList must implement the Comparable interface to be sorted
		//Or pass in a comparator
		Collections.sort(numList);
		
		
		System.out.println(numList);

	}

}

Output:

[1, 2, 4, 5, 7]

2)

package com.beginner.examples;

import java.util.Comparator;

public class CustomComparator implements Comparator {

	@Override
	public int compare(Integer o1, Integer o2) {
		
		int result = o2-o1;
		
		return result;
	}

	
}

3)

package com.beginner.examples;

import java.util.ArrayList;
import java.util.Collections;

public class SortOfArrayListExample2 {

	public static void main(String[] args) {
		
		ArrayList numList = new ArrayList();

		numList.add(1);
		numList.add(4);
		numList.add(7);
		numList.add(5);
		numList.add(2);
		
		//Sort by custom comparator
		Collections.sort(numList,new CustomComparator());
		
		System.out.println("In descending order:"+numList);
	}

}

Output:

In descending order:[7, 5, 4, 2, 1]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments