• September 3, 2014
  • Core Java
  • Comments Off on TreeMap in java

TreeMap in java

TreeMap:

TreeMap extends AbstractMap class and implements the NavigableMap  interface. It contains the elements in key-value pair form. It maintains ascending order for its elements. It not allowed duplicate key.

Note: A TreeMap can have only one null key but can have multiple null values.

TreeMap example:

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 javawithease
 */
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: PriorityQueue in java with example.
Previous Topic: LinkedHashMap in java with example.

Related Topics:

Collection framework in java.
Collection interfaces in java.
Collection interface in java with example.
Set interface in java with example.
SortedSet interface in java with example.
List interface in java with example.
Map interface in java with example.
Daemon thread in java in java with example.
SortedMap interface in java with example.
Queue interface in java with example.
Deque interface in java with example.
Enumeration interface in java with example.
Collection classes in java with example.
HashSet in java with example.
LinkedHashSet in java with example.
TreeSet in java with example.
ArrayList in java with example.
LinkedList in java with example.
HashMap in java with example.
LinkedHashMap in java with example.
TreeMap in java with example.
PriorityQueue in java with example.
ArrayDeque in java with example.
Abstract classes in collection framework in java with example.
Sorting in java with example.
Comparable interface in java with example.
Comparator interface in java with example.
Properties class in java with example.
Hashtable in java with example.
ListIterator interface in java with example.

 


Comments are closed.