Get comparator in reverse order
static<T> Comparator<T> reverseOrder()
- Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
static<T> Comparator<T> reverseOrder(Comparator<T> cmp)
- Returns a comparator that imposes the reverse ordering of the specified comparator.
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
public class MainClass {
public static void main(String args[]) throws Exception {
String elements[] = { "S", "P", "E","G", "P" };
Set set = new TreeSet(Collections.reverseOrder());
for (int i = 0, n = elements.length; i < n; i++) {
set.add(elements[i]);
}
System.out.println(set);
}
}
The output:
[S, P, G, E]
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
public class MainClass {
public static void main(String args[]) {
LinkedList<Integer> ll = new LinkedList<Integer>();
ll.add(-8);
ll.add(20);
ll.add(-20);
ll.add(8);
Comparator<Integer> r = Collections.reverseOrder();
Collections.sort(ll, r);
System.out.print("List sorted in reverse: ");
for(int i : ll){
System.out.print(i+ " ");
}
System.out.println();
Collections.shuffle(ll);
System.out.print("List shuffled: ");
for(int i : ll)
System.out.print(i + " ");
System.out.println();
System.out.println("Minimum: " + Collections.min(ll));
System.out.println("Maximum: " + Collections.max(ll));
}
}
The output:
List sorted in reverse: 20 8 -8 -20
List shuffled: 20 -20 -8 8
Minimum: -20
Maximum: 20
Home
Java Book
Collection
Java Book
Collection
Collections:
- Collections
- Get empty collection from Collections
- Do binary search
- Copy value to a List
- Get Enumeration from collection, create list from Enumeration
- Fill a list
- Get the max and min value from a Collection
- Fill n Copy object to a list
- Replace value in a list
- Reverse a list
- Get comparator in reverse order
- Rotate and shuffle a list
- Create singleton
- Sort a list
- Swap element in a list
- Get a synchronized collection
- Return an unmodifiable view of collections