LinkedHashMap class in Java with Example

HashMap in Java provides quick insert, search and delete operations. However it does not maintain any order on elements inserted into it. If we want to keep track of order of insertion, we can use LinkedHashMap.
LinkedHashMap is like HashMap with additional feature that we can access elements in their insertion order.


LinkedHashMap<Integer, String> lhm = new LinkedHashMap<Integer, String>();
  • A LinkedHashMap contains values based on the key. It implements the Map interface and extends HashMap class.
  • It contains only unique elements (See this for details)..
  • It may have one null key and multiple null values (See this for details).
  • It is same as HashMap with additional feature that it maintains insertion order. For example, when we ran the code with HashMap, we got different oder of elements (See this).

Basic Operations of LinkedHashMap class:

// Java program to demonstrate working of LinkedHashMap
import java.util.*;

public class BasicLinkedHashMap
    public static void main(String a[])
        LinkedHashMap<String, String> lhm =
                       new LinkedHashMap<String, String>();
        lhm.put("one", "");
        lhm.put("two", "");
        lhm.put("four", "");

        // It prints the elements in same order as they were inserted    

        System.out.println("Getting value for key 'one': " + lhm.get("one"));
        System.out.println("Size of the map: " + lhm.size());
        System.out.println("Is map empty? " + lhm.isEmpty());
        System.out.println("Contains key 'two'? "+ lhm.containsKey("two"));
        System.out.println("Contains value ''? "
                           + lhm.containsValue(""));
        System.out.println("delete element 'one': " + lhm.remove("one"));


Getting value for key 'one':
Size of the map: 3
Is map empty? false
Contains key 'two'? true
Contains value ''? true
delete element 'one':


This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Recommended Posts:

2.1 Average Difficulty : 2.1/5.0
Based on 8 vote(s)