CodesJava

Easy learning with example program codes

how to iterate 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.

We can use iterator interface. It is a universal iterator as we can apply it to any Collection object. It provides the functionality of read and remove operations. Collection interface provides iterator() method to get the Iterator object. Iterator interface have following to methods to iterate collection objects.

hasNext(): It returns true if the iteration has more elements.
next(): It returns the next element in the iteration.

Example

package com.codesjava;
 
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
 
public class Test {
	public static void main(String args[]){
		//Create TreeMap object.
		TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();
 
		//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
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki