Comparison on HashMap, TreeMap, LinkedHashMap:
HashMap | TreeMap | LinkedHashMap |
No Duplicate Key are allowed, But values can be anything. | No Duplicate Key are allowed, But values can be anything. | No Duplicate Key are allowed, But values can be anything. |
Orders cannot be predicted, in can print the data in any order | TreeMap will follow the natural ordering of key, All Keys in the TreeMap should be in same type | LinkedHashMap insertion order will be maintained, Adding duplicate key will not affect the existing order. |
Supports 1 null Key | Does not support null key elements | Supports 1 null elements |
Gives good performance on read and write | Slow when compared with HashMap, use this only when you need ordering by default | Slow when compared with HashMap, but faster than TreeMap, Use this if you need to maintain the insertion order of the data. |
Example:
package com.candidjava.core; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.TreeMap; public class MapComparison { public static void main(String[] args) { HashMap<String, String> hm=new HashMap<String, String>(); hm.put("name","candid"); hm.put("email","candid@gmail.com"); hm.put("password", "123456"); hm.put("street", "shanthi nagar"); hm.put("password", "789"); hm.put("altemail", null); hm.put("altph", null); TreeMap<String, String> tm=new TreeMap<String, String>(); tm.putAll(hm); LinkedHashMap<String, String> lhm=new LinkedHashMap<String, String>(); lhm.putAll(hm); System.out.println("HashMap: " + hm); System.out.println("TreeMap: " + tm); System.out.println("LinkedHashMap: " + lhm); } }
Output:
HashMap: {password=789, altemail=null, street=shanthi nagar, name=candid, altph=null, email=candid@gmail.com} TreeMap: {altemail=null, altph=null, email=candid@gmail.com, name=candid, password=789, street=shanthi nagar} LinkedHashMap: {password=789, altemail=null, street=shanthi nagar, name=candid, altph=null, email=candid@gmail.com}