Thursday, 20 June 2013

SortedMap Interface in JAVA

The Collection Framework provides a special Map interface for maintaining elements in a sorted order called SortedMap.A SortedMap is a Map that maintains its entries in ascending order, sorted according to the keys' natural ordering, or according to a Comparator provided at the time of the SortedMap creation. The SortedMap interface extends Map. It ensures that the entries are maintained in ascending key order.

NOTE: SortedMap methods throw a NoSuchElementException when no items are in the invoking map. A ClassCastException is thrown when an object is incompatible with the elements in a map. A NullPointerException is thrown if an attempt is made to use a null object when null is not allowed in the map.

Following is the SortedMap interface.

public interface SortedMap<K, V> extends Map<K, V>{
    Comparator<? super K> comparator();
    SortedMap<K, V> subMap(K fromKey, K toKey);
    SortedMap<K, V> headMap(K toKey);
    SortedMap<K, V> tailMap(K fromKey);
    K firstKey();
    K lastKey();
}

Following table shows the list of methods available in Map interface:
Example:

package com.sample.javase.testing;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

public class SortedMapInterfaceExample {

/**
* @param args
*/
public static void main(String[] args) {

SortedMap<String, String> sortedMap = new TreeMap<String, String>();
sortedMap.put("oop1", "java");
sortedMap.put("oop2", "c++");
sortedMap.put("oop3", "objective-c");
System.out.println(sortedMap);// it maintains ascending order.
System.out.println("first key is" + sortedMap.firstKey());
System.out.println("Last key is " + sortedMap.lastKey());

/**
* Following lines of code specifies hoe to get the map values form
* iterator. For this first we need to get entry set or key set from
* map.Here we are using entryset() method.
*/
Set set = sortedMap.entrySet();
for (Iterator iterator = set.iterator(); iterator.hasNext();) {

Map.Entry entry = (Entry) iterator.next();
System.out.println("key is " + entry.getKey());
System.out.println("value is " + entry.getValue());
}
/**
* Following lines of code specifies hoe to get the map values form
* iterator. For this first we need to get entry set or key set from
* map.Here we are using keyset() method.
*/
Set set2 = sortedMap.keySet();
for (Iterator iterator = set2.iterator(); iterator.hasNext();) {
Object object = (Object) iterator.next();
System.out.println("key is " + object + "value is " + sortedMap.get(object));
}
}

}

No comments:

Post a Comment