We can use entrySet() method to get entry set from treemap in java.
entrySet(): Returns a Set that contains the entries of this map. The set contains objects of type Map.Entry. It provides a set-view of this map.
Syntax:
public Set entrySet()
Example
package com.w3schools; import java.util.Map.Entry; 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); Set<Entry<Integer, String>> entires = treeMap.entrySet(); for(Entry<Integer,String> entry:entires){ System.out.println(entry.getKey()+" - "+entry.getValue()); } } } |
Output
TreeMap elements: TreeMap elements: {1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy} 1 - Munish 2 - Sunil 3 - Pardeep 4 - Roxy 5 - Sandy |