SortedMap interface in java

SortedMap interface:

SortedMap interface extends Map interface. It maintains its entries in ascending key order.

Commonly used methods of SortedMap interface:

1. comparator(): Returns comparator for this sorted map. It returns null if the natural ordering is used for this map.

Syntax: public Comparator comparator().

2. firstKey(): Returns the first key in this map.

Syntax: public Object firstKey ( ).

3. headMap(Object end): Returns a SortedMap containing those elements less than end that are contained in this sorted map.

Syntax: public SortedMap headMap(Object end).

4. lastKey(): Returns the last key in this sorted map.

Syntax: public Object lastKey().

5. subMap(Object start, Object end): Returns a SortedMap containing those elements between start and end -1.

Syntax: public SortedMap subMap(Object start, Object end).

6. tailMap(Object start): Returns a map containing those entries with keys that are greater than or equal to start.

Syntax: public SortedMap tailMap(Object start)

 A simple example of TreeMap class to explain few methods of SortedMap interface.

TreeMapTest.java

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
 
/**
 * This class is used to show the TreeMap functionality.
 * @author w3schools
 */
public class TreeMapTest {
	public static void main(String args[]){
		//Create TreeMap object.
		Map treeMap = new TreeMap();
 
		//Add objects to the TreeMap.
		treeMap.put(4, "Roxy");
		treeMap.put(2, "Sunil");
		treeMap.put(5, "Sandy");
		treeMap.put(1, "Munish");
		treeMap.put(3, "Pardeep");
 
		//Print the TreeMap object.
		System.out.println("TreeMap elements:");
		System.out.println(treeMap);
 
		//Get iterator
		Set set=treeMap.entrySet();  
		Iterator iterator=set.iterator();  
 
		//Print the TreeMap elements using iterator.
		System.out.println("TreeMap elements using iterator:");
		while(iterator.hasNext()){
		   Map.Entry mapEntry=(Map.Entry)iterator.next();  
		   System.out.println("Key: " + mapEntry.getKey() + ", " +
		   		"Value: " + mapEntry.getValue());  
		}  
	}
}

Output:

TreeMap elements:
{1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy}
TreeMap elements using iterator:
Key: 1, Value: Munish
Key: 2, Value: Sunil
Key: 3, Value: Pardeep
Key: 4, Value: Roxy
Key: 5, Value: Sandy

Download this example.
 
Next Topic: Queue interface in java with example.
Previous Topic: Daemon thread in java in java with example.