LinkedHashMap overview

LinkedHashMap is based on HashTable and LinkedList implementation

Main features of LinkedHashMap


It also stores elements in the key-value pair like any other Map

It maintains the Insertion order of elements

It can have Null Key and Null Values

Value can be retrieved by passing key

If passed key is not exist in the Map then value returned will be Null

LinkedHashMap can be created using constructor as below

  1. LinkedHashMap<Integer,String> lhm = new LinkedHashMap<Integer,String>();
LinkedHashMap<Integer,String> lhm = new LinkedHashMap<Integer,String>();


Important methods in LinkedHashMap

put(Object key, Object value)

This method stores the specified value and associates it with the specified key in this map.

get(Object key)

This method will return the value associated with a specified key in this map.

We can add key value pair as below

  1. lhm.put(1,”one”);
lhm.put(1,”one”);


We can retrieve value for the specific key as

  1. lhm.get(1);
lhm.get(1);


Example

  1. import java.util.*;
  2. public class LinkedHashMapExample {
  3. public static void main(String args[]) {
  4.  
  5. LinkedHashMap<Integer, String> lhm = new LinkedHashMap<Integer, String>();
  6.  
  7.       lhm.put(1, "One");
  8.       lhm.put(2, "Two");
  9.       lhm.put(3, "Three");
  10.       lhm.put(4, "Four");
  11.       lhm.put(5, "Five");
  12. System.out.println(lhm);
  13. System.out.println("Value for the key 1 is "+lhm.get(1));
  14. System.out.println("Value for the key 10 is "+lhm.get(10));
  15. }
  16. }
import java.util.*;
public class LinkedHashMapExample {
public static void main(String args[]) {
 
LinkedHashMap<Integer, String> lhm = new LinkedHashMap<Integer, String>();
 
      lhm.put(1, "One");
      lhm.put(2, "Two");
      lhm.put(3, "Three");
      lhm.put(4, "Four");
      lhm.put(5, "Five");
System.out.println(lhm);
System.out.println("Value for the key 1 is "+lhm.get(1));
System.out.println("Value for the key 10 is "+lhm.get(10));
}
}
Note : We can see that corresponding value for existing key is retrieved and value for non-existing key is 
           returned as Null

When to use LinkedHashMap ?

Whenever we want to store data in key-value pair format and Whenever we need to maintain the order of insertion

When not to use LinkedHashMap ?

Whenever we don’t want to store key-vallue pair data and whenever we don’t worry about the order of insertion

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on