Sorted Map Interface
In Java, SortedMap is an interface of Collection framework. SortedMap extends Map interface and also provide the ordering of the elements. Traversing the sorted elements becomes easier.
Below are the methods of SortedMap Interface.
S.no. |
Methods |
Description |
1 |
subMap(K fromKey, K toKey) |
It is used to view the elements from a given range |
2 |
headMap(K toKey) |
It is used to get the key which is less than than the toKey. |
3 |
tailMap(K fromKey) |
It is used to get the key which is greater than or equal to the fromKey. |
4 |
firstKey() |
It is used to get the lowest key. |
5 |
lastKey() |
It is used to get the highest key. |
6 |
comparator() |
It is used to get the comparator used in the Map. |
7 |
values() |
It is used to get the values of the Map |
8 |
keySet() |
It is used to get the set view from the Map. |
9 |
entrySet() |
It is used to get the set view of the mapping which are contained in the map. |
Example:
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
public class SortedMapDemo1
{
public static void main(String[] args)
{
SortedMap<Integer, String> a = new TreeMap<Integer, String>();
a.put(new Integer(2), "Red");
a.put(new Integer(3), "Pink");
a.put(new Integer(5), "Yellow");
a.put(new Integer(4), "Black");
a.put(new Integer(1), "Green");
Set b = a.entrySet();
Iterator i = b.iterator();
while (i.hasNext())
{
Map.Entry c = (Map.Entry)i.next();
int key1 = (Integer)c.getKey();
String value1 = (String)c.getValue();
System.out.println("Key : " + key1 + " || value : " + value1);
}
}
}