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.

Syntax

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", "practice.geeksforgeeks.org");
        lhm.put("two", "code.geeksforgeeks.org");
        lhm.put("four", "quiz.geeksforgeeks.org");

        // It prints the elements in same order as they were inserted    
        System.out.println(lhm);

        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 'practice.geeksforgeeks.org'? "
                           + lhm.containsValue("practice.geeksforgeeks.org"));
        System.out.println("delete element 'one': " + lhm.remove("one"));
        System.out.println(lhm);
    }
}

Output:

{one=practice.geeksforgeeks.org, two=code.geeksforgeeks.org, four=quiz.geeksforgeeks.org}
Getting value for key 'one': practice.geeksforgeeks.org
Size of the map: 3
Is map empty? false
Contains key 'two'? true
Contains value 'practice.geeksforgeeks.org'? true
delete element 'one': practice.geeksforgeeks.org
{two=code.geeksforgeeks.org, four=quiz.geeksforgeeks.org}

collectionjava

This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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)