Collection public static Comparator reverseOrder() Method Example Program


Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.

Program

package com.candidjava;

import java.util.*;
/**
 * 
 * @author karthikeyan.T
 *  @description : the following code shows how to use
 *              Collections.reverseorder()
 *              method.
 */
public class CollectionsReverseOrder {

	public static void main(String args[]) {
		LinkedList<Integer> list = new LinkedList();
		list.add(-32);
		list.add(65);
		list.add(-72);
		list.add(49);
		Comparator cmp = Collections.reverseOrder();
		Collections.sort(list, cmp);
		System.out.println("List sorted in ReverseOrder: ");
		for (int i : list) {
			System.out.println(i + " ");
		}
	}
}

Output

List sorted in ReverseOrder: 
65 
49 
-32 
-72 

Explanation

public 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. (The natural ordering is the ordering imposed by the objects' own compareTo method.) This enables a simple idiom for sorting (or maintaining) collections (or arrays) of objects that implement the Comparable interface in reverse-natural-order. For example, suppose a is an array of strings. Then:
          Arrays.sort(a, Collections.reverseOrder());
 
sorts the array in reverse-lexicographic (alphabetical) order.
The returned comparator is serializable.

Returns:
A comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
See Also:
Comparable


Related Post

Comments


©candidjava.com