0
Sponsored Links


Ad by Google
In this post we are going to show you, What is LinkedHashMap? When to use LinkedHashMap? and How to use LinkedHashMap?. In our previous post we have already seen an example of HashMap and Hashtable with running sample java program.

What is LinkedHashMap?

Well LinkedHashMap is an implementation of java.util.Map interface and also extends HashMap class. The LinkedHashMap allows all the optional operations of Map interface and behaves same as HashMap.

The implementation of LinkedHashMap is based on doubly-linked-list, So the insertion order is maintained in LinkedHashMap unlike HashMap. The LinkedHashMap allows null as a key and any number of null values unlike Hashtable. It provides basic operations(add, contains and remove) performance on constant time.

Of course, it takes more memory space as compared to HashMap, due to it's doubly-linked-list implementation. Iteration on LinkedHashMap provides time proportional to the size of the map.

For performance point of view LinkedHashMap has two parametrized constructor with initial capacity and load factor. The initial capacity is basically number of buckets, the default initial capacity is 16. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased, default load factor is .75

When to use LinkedHashMap?

You can select LinkedHashMap whenever you need to maintained the insertion order of your elements.Because LinkedHashMap is maintained it's insertion order due to doubly-linked-list implementation and also LinkedHashMap gives you better performance in terms of iteration, It requires time proportional to the size of the map unlike HashMap.

How to use LinkedHashMap?

package com.javamakeuse.poc;

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample {
 public static void main(String[] args) {
  Map<String, Double> saleMap_2015 = new LinkedHashMap<>();
  saleMap_2015.put("Jan", 30000d);
  saleMap_2015.put("Feb", 25000d);
  saleMap_2015.put("March", 31000d);

  for (String key : saleMap_2015.keySet()) {
   // getting elements from the map
   System.out.println(key + " sale value - " + saleMap_2015.get(key));
  }
 }
}

OUT PUT:Insertion order is maintained.
Jan sale value - 30000.0
Feb sale value - 25000.0
March sale value - 31000.0


Sponsored Links

0 comments:

Post a Comment