Example of sorting an ArrayList in reverse order in Java
Hi, Today program demonstrates how to sort an ArrayList of integers in reverse order in Java using the Collections.sort method with the Collections.reverseOrder() method. It creates a new ArrayList of integers, adds four elements to it, and prints the contents of the ArrayList before and after sorting in reverse order.
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(2);
numbers.add(8);
numbers.add(1);
System.out.println("Before sorting: " + numbers);
Collections.sort(numbers, Collections.reverseOrder());
System.out.println("After sorting in reverse order: " + numbers);
}
}
In Above example, we create a new ArrayList of integers, add four elements to it, and print the contents of the ArrayList before sorting. We then use the Collections.sort method with the Collections.reverseOrder() method to sort the ArrayList in reverse order. Finally, we print the contents of the ArrayList after sorting.
The output of this program will be:
Before sorting: [5, 2, 8, 1]
After sorting in reverse order: [8, 5, 2, 1]
Certainly, here's an example of sorting an ArrayList in reverse order in Java, showing both the old and new methods:
Old method using Comparator:
List<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(2);
numbers.add(8);
numbers.add(1);
Comparator<Integer> reverseComparator = new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
};
Collections.sort(numbers, reverseComparator);
System.out.println(numbers); // prints [8, 5, 2, 1]
New method using Stream API:
List<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(2);
numbers.add(8);
numbers.add(1);
List<Integer> reversedNumbers = numbers.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
System.out.println(reversedNumbers); // prints [8, 5, 2, 1]
Labels: core java, java collection tutorial, programming
0 Comments:
Post a Comment
Note: only a member of this blog may post a comment.
<< Home