Tuesday, September 13, 2011

Comparator Example in java


//ComparatorExample.java
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class ComparatorExample
{
public static void main(String arg[])
{
System.out.println("Print decreasing order using TreeSet");

Comparator c = Collections.reverseOrder();

Set s = new TreeSet(c);
s.add(1);
s.add(21);
s.add(12);
s.add(13);
s.add(4);
s.add(15);
s.add(16);
s.add(77);
s.add(18);
s.add(29);

Iterator it = s.iterator();
while (it.hasNext())
{
System.out.println(it.next());
}

}
}


Output =>
Print decreasing order using TreeSet
77
29
21
18
16
15
13
12
4
1

No comments:

Post a Comment