SortedMap Interface

If we wish to maintain a map in ascending key order, we need to use the TreeMap implementation of the Map interface.

MapExample

import java.util.*;


public class MapExample
{

public static void main(String[] args)
{
Map m = new TreeMap();
m.put(new Integer(1),”Smith”);
m.put(new Integer(2),”Jones”);
m.put(new Integer(3),”Smith”);
m.put(new Integer(4),”Brown”);
m.put(new Integer(5),”Able”);


Collection c = m.keySet();
Iterator i = c.iterator();
while (i.hasNext() )
{
System.out.print( m.get(i.next()) + " ");
}
}
}


No other changes need to be made. The program output will now be

Smith Jones Smith Brown Able

The SortedMap interface inherits all the methods of the Map interface. In addition, SortedMap provides a number of methods, such as firstKey and lastKey, which make sense only for a map that is sorted. There is only one implementation of SortedMap, namely, TreeMap. To use the noninherited methods, we need to replace line 6 with

SortedMap m = new TreeMap();

The statements

System.out.println(''first key: " + m.firstKey());
System.out.println("last key: " + m.lastKey());


will produce the output

first key: 1
last key: 5

No comments:

Post a Comment