sorting
collections
■ To sort a Set, make it a TreeSet. ie.
Set
hs = new HashSet( );
hs.add("5");
hs.add("3");
hs.add("1");
hs.add("2");
hs.add("4");
System.out.println(
hs ); // HashSet is
unordered
Set
ts = new TreeSet(hs);
System.out.println(ts); // TreeSet is ordered
■ To sort a Map, make it a TreeMap. i.e
HashMap
hm = new HashMap();
Integer
one = new Integer( 1 );
Integer
two = new Integer( 2 );
Integer
three = new Integer( 3 );
Integer
four = new Integer( 4 );
Integer
five = new Integer( 5 );
hm.put(
five, "five" );
hm.put(
two, "two" );
hm.put(
three, "three" );
hm.put(
one, "one" );
hm.put(
four, "four" );
System.out.println(
hm ); // HashMap is
unordered
Map
tm = new TreeMap(hm);
System.out.println(
tm ); //TreeMap is
ordered
■ To sort a List, use Collections.sort(list); . It sorts the list directly – doesn’t return anything.
Note that it throws a ClassCastException if it encounters unlike elements (of different types). i.e
String[
] array = {"5", "2", "1", "4",
"3"};
ArrayList myList = new ArrayList (Arrays.asList(array) );
System.out.println("List
contains: " + myList);
Collections.sort(myList);
System.out.println("List
now contains: " + myList);
■ To reverse their order, there’s also a Collections.sort(list,
Comparator) which lets you specify a reversing Comparator to be
used. See reversing their order. i.e.
Collections.sort(myList,
Collections.reverseOrder( ));