What is TreeMap

What is TreeMap

Answer: public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, Serializable

In java TreeMap class is an example of SortedMap where the order of the keys could be sorted and by default when we store data its keys will be sorted in ascending order. Please see java example below:

package com.javahonk.treemap;

import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapTest {
    
    public static void main(String args[]){
    
    TreeMap< String, Double> treeMap = 
        new TreeMap<String, Double>();
    
    treeMap.put("John Landy", 1000.23);
    treeMap.put("Ramesh Arrepu", 1000.30);
    treeMap.put("Yan", 1000.33);
    treeMap.put("Java Honk", 1000.44);
    
    Set<Entry<String, Double>> set = treeMap.entrySet();
    System.out.println("Value will in sorted "
        + "ascending order:\n");
    for (Entry<String, Double> entry : set) {
        System.out.println("Key: "+entry.getKey()
            +" Value: "+entry.getValue());      
    }
    
    
    } 

}

Output:

What is TreeMap

Leave a Reply

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