How you decide when to use HashMap or TreeMap

How you decide when to use HashMap or TreeMap

Answer: Below are points:

HashMapTreeMap
It uses a hash table to store the map (Internally it uses array and hashing function to store elements)TreeMap creates maps that stored in tree structure
Insert or delete is costly because hashing converts key into index where the object will be stored and new copies key/value to new arrayTreeMap store data in sorted tree structure it never need to allocate more space and copy the over it
HashMap provides O(1) look up timeTreeMap provides O(log n) lookup time
Because It uses a hash table to store the map. This technique allows total execution time of get( ) method and put( ) method remain constant for large sets as well.TreeMap offers effective means of storingKey and value pairs in sorted order and allows fast retrieval
HashMap doesn’t give any guarantees that  elements will be in sorted orderTreemap gives guarantees that elements will be sorted order and by default is ascending key order.

Decision: Because HahsMap gives better performance if you don’t need sorting then go for HashMap otherwise TreeMap would be choice. You have also option available to use LinkdeHashMap which is same fast as HashMap including it gives remove/add/contains functionality and also maintains insertion order.

Please have example java code  for HashMap and TreeMap:

package com.javahonk.hashmaptable;

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

public class HashMapTableTest {

    public static void main(String[] args) {

    Map<String, String> map = 
            new HashMap<String, String>();
    map.put("Java", "Java");
    map.put("Honk", "Honk");

    System.out.println("HashMap example");
    Iterator<Entry<String, String>> it = 
            map.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String,String> entry = 
                (Map.Entry<String,String>) it.next();
        String key = (String) entry.getKey();
        String val = (String) entry.getValue();
        System.out.println("Key: " + key + "  Value: " + val);

    }

    System.out.println("\nTreeMap example");

    TreeMap<String, Double> treeMap = new TreeMap<String, Double>();

    treeMap.put("Java Honk", new Double(2000.24));
    treeMap.put("Bill Peng", new Double(1500.22));
    treeMap.put("Tom Nally", new Double(2522.63));

    Set<Map.Entry<String, Double>> set = treeMap.entrySet();

    for(Map.Entry<String, Double> me : set) {
    System.out.print(me.getKey() + ": ");
    System.out.println(me.getValue());
    }
    System.out.println();

    }

}

 

Output:

How you decide when to use HashMap or TreeMap

Leave a Reply

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