Map

A primary cause of complexity is that software vendors uncritically adopt almost any feature that users want. Niklaus Wirth

LinkedHashMap

Language Java | Level Intermediate | Category Java collections framework (JCF) | 2015-07-22 23:23:33

0 Comments


Definition

LinkedHashMap is a Hash table and linked list implementation of the Map interface which will maintain the insertion order. It stores the insertion order using doubly linked list which will take more memory compare than the hash map.

Character

It maintains insertion order using doubly linked list.
Linked hash map generated from existing map interface.
The constructor provides option whose order of iteration is the order in which its entries were last accessed.
It does not synchronize when multiple threads access using iterator.
The access-ordered linked hash maps, merely querying the map with getting is a structural modification.
It throw ConcurrentModificationException.
The fail-fast behavior of iterators should be used only to detect bugs.

source Code

								
package com.careerdrill.collections.map;

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

public class HashMapUse {

	public static void main(String[] args) {
		Map< String,String > mMap = new HashMap< String,String >();
		mMap.put("C++", "Object oriented programming language");
		mMap.put("Java", "Platform independent language");
		mMap.put("SQL", "Enterprise database Software");
		mMap.put("C#", "Microsoft Programming language");

		Iterator< Entry < String, String > > iter = mMap.entrySet().iterator();

		while (iter.hasNext()) {
			Entry< String, String > mEntry = iter.next();
			System.out.println(mEntry.getKey() + " : " + mEntry.getValue());
		}

		mMap.put("C#", "Microsoft .NET language");

		System.out.println("Get value of 'C#': " + mMap.get("C#"));

	}

}
						

Output

    					 
Add Programming languages and year to the Linkedhashmap
Contents of LinkedHashMap : {C=1972, CPP=1983, java=1995, Javascript=1995, Python=1991}
Values of map after iterating over it : 
C:	1972
CPP:	1983
java:	1995
Javascript:	1995
Python:	1991
    					 
					    

Comparison

Hashmap LinkedHashmap Treemap
Hashmap does not maintain any order. LinkedHashmap maintains insertion order. Treemap provides natural sorting.
LinkedHashmap and Hashmap allow null. LinkedHashmap and Hashmap allow null. Treemap does not allow null.
O(n) O(1) O(logn)
Implemented based on buckets. Maintaining insertion order using double buckets. Internally implement based on red block tree.
Compare using equals() and hashCode() methods. Compare using equals() and hashCode() methods. Comparable or comparator interface implementation.

When to use

When you need to maintain the insertion order in addition to unique elements, you can use LinkedHashmap.

0 Comments



Please login to add comments.