sort list in reverse order in java

There are several methods to sort list in reverse order in java.

Using Java 8 :- We can sort a list in reverse order using Stream in Java 8.sort the stream in reverse order by using stream.sorted method to passing Comparator.reverseOrder() for natural order.
here use compareTo method for reverse order and to collect all element using Collectors.toList().

Using Collections.sort() :- Collections.sort() method sorted the list by comparator in natural order.this method come inside java.util.Collections class.

				
					import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class SortAndReverseOrder {
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>();
		list.add(1);
		list.add(6);
		list.add(9);
		list.add(2);
		list.add(7);

		// from stream and sorted method
		List test = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
		System.out.println("sort and reverse from stream method :- " + test);

		// from Collections.sort method
		Collections.sort(list, Comparator.reverseOrder());
		System.out.println("sort and reverse from Collections method :- " + list);
	}
}
				
			

Output :-
sort and reverse from stream method :- [9, 7, 6, 2, 1]
sort and reverse from Collections method :- [9, 7, 6, 2, 1]

Leave a Comment

Your email address will not be published. Required fields are marked *