coderz.py

Keep Coding Keep Cheering!

SortedMap Interface in Java

java thread class

SortedMap is a collection framework interface. It guarantees that the entries are kept in ascending key order. This interface is an extension of the Map interface. TreeMap is the class that implements this interface.

Type Parameters:

  • K – the type of keys maintained by this map
  • V – the type of mapped values

SortedMap’s parent interface is Map. It has two subinterfaces: ConcurrentNavigableMap<K, V> and NavigableMap<K, V>.

Methods of SortedMap Interface:
Method Description
Comparator<? super K> comparator()Returns the comparator used to order the keys in this map, or null if the keys in this map are ordered naturally.
Set<Map.Entry<K,V>>entrySet()This method returns a Set view of the mappings in this map.
K firstKey()This function returns the first (lowest) key in this map.
SortedMap<K,V> headMap(K toKey)This method returns a view of the map portion whose keys are less than toKey.
Set<K> keySet()This method returns a Set view of the keys in this map.
K lastKey()Returns the most recent (highest) key in this map.
SortedMap<K,V> subMap(K fromKey, K toKey)Returns a view of the portion of this map whose keys range from fromKey to toKey, inclusively.
SortedMap<K,V> tailMap(K fromKey)This method returns a view of the section of this map whose keys are greater than or equal to fromKey.
Collection<V> values()This method returns a Collection view of the values in this map.
Example:
// Java code to demonstrate SortedMap Interface
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

public class Coderz {
	public static void main(String[] args)
	{
		SortedMap<Integer, String> sm
			= new TreeMap<Integer, String>();
		sm.put(new Integer(2), "C");
		sm.put(new Integer(3), "JAVA");
		sm.put(new Integer(5), "C++");
		sm.put(new Integer(4), "SQL");
		sm.put(new Integer(1), "RUBY");
		Set s = sm.entrySet();

		// Using iterator in SortedMap
		Iterator i = s.iterator();

		// Traversing map. Note that the traversal
		// produced sorted (by keys) output .
		while (i.hasNext()) {
			Map.Entry m = (Map.Entry)i.next();

			int key = (Integer)m.getKey();
			String value = (String)m.getValue();

			System.out.println("Key : " + key
							+ " value : " + value);
		}
	}
}
Output:
Key : 1 value : RUBY
Key : 2 value : C
Key : 3 value : JAVA
Key : 4 value : SQL
Key : 5 value : C++

Note: also read about the IdentityHashMap class in Java

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Comment

Your email address will not be published. Required fields are marked *

Advertisement