LinkedHashMap

Java LinkedHashMap Example

In this example, we will show how to use the Java LinkedHashMap class. LinkedHashMap is an implementation of java.util.Map interface with predictable iteration order (the order of insertion) i.e. LinkedHashMap will iterate in the order in which the entries were put into the map.

1. Introduction

This implementation differs from HashMap in the way that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map. The insertion order is not affected if a key is re-inserted into the map. Performance of LinkedHashMap is slightly below than that of HashMap, due to the added expense of maintaining the linked list.

The other two important implementations of Map interface are java.util.HashMap and java.util.TreeMap. They offer mostly the same functionality. The most important difference is the order in which iteration through the entries will happen. HashMap makes no guarantee about the order. The order can even change completely when new elements are added. TreeMap will iterate according to the “natural ordering” of the keys according to their compareTo() method (or an externally supplied java.util.Comparator). LinkedHashMap will iterate in the order in which the entries were put into the map.

2. Example of Java LinkedHashMap

Create a java class named LinkedHashMapExample.java with the following code:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.javacodegeeks.corejava;
 
import java.util.LinkedHashMap;
import java.util.Map;
 
public class LinkedHashMapExample {
 
    public static void main(String[] args) {
 
        // Map representing (Company, share price) as (key, value) pair
        Map<String, Double> linkedHashMap = new LinkedHashMap<String, Double>();
        linkedHashMap.put("Apple", new Double(91.98));
        linkedHashMap.put("Sony", new Double(16.76));
        linkedHashMap.put("Dell", new Double(30.47));
        linkedHashMap.put("HP", new Double(33.91));
        linkedHashMap.put("IBM", new Double(181.71));
 
        // Displaying the contents of the LinkedHashMap
        System.out.println("Contents of LinkedHashMap : " + linkedHashMap);
 
        // One of the ways of iterating over the map
        // Notice the order of the elements is same as the order of insertion
        System.out.println("\nValues of map after iterating over it : ");
        for (String key : linkedHashMap.keySet()) {
            System.out.println(key + ":\t" + linkedHashMap.get(key));
        }
 
        // Getting the value for a particular key
        System.out.println("\nThe current share price of HP is : "
                + linkedHashMap.get("HP"));
 
        // Getting the size of the LinkedHashMap
        System.out
                .println("\nThe size of the LinkedHashMap is : " + linkedHashMap.size());
 
        // Checking whether the LinkedHashMap is empty
        System.out.println("\nIs LinkedHashMap empty? : " + linkedHashMap.isEmpty());
 
        //Checking whether Map contains a particular key or value
        System.out.println("\nLinkedHashMap contains Sony as key? : " + linkedHashMap.containsKey("Sony"));
        System.out.println("LinkedHashMap contains 999.0 as value? : " + linkedHashMap.containsValue(999.0));
         
        // Removing a particular value
        System.out.println("\nRemove entry for Dell : " + linkedHashMap.remove("Dell"));
        System.out.println("Content of LinkedHashMap removing Dell: " + linkedHashMap);
 
        // Clearing the LinkedHashMap
        linkedHashMap.clear();
        System.out.println("\nContent of LinkedHashMap after clearing: " + linkedHashMap);
    }
}

Let’s explain the above code.

First, we create a LinkedHashMap object which will hold Company name as key and its share price as value. Now we insert the (key, value) pair to the map using the map’s put method. After that, we use some of the basic methods of Map interface to retrieve/manipulate the data. Brief description of the methods is given below:

V get(Object key): This method returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

int size(): Returns the number of key-value mappings in this map.

boolean isEmpty(): Returns true if this map contains no key-value mappings.

boolean containsKey(Object key): This method returns true if this map maps one or more keys to the specified value.

boolean containsValue(Object value): This method returns true if this map maps one or more keys to the specified value.

V remove(Object key): Removes the mapping for the specified key from this map if present.

void clear(): This method removes all of the mappings from this map.

If we run the above code, we will have the following results:

Output

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
Contents of LinkedHashMap : {Apple=91.98, Sony=16.76, Dell=30.47, HP=33.91, IBM=181.71}
 
Values of map after iterating over it :
Apple:  91.98
Sony:   16.76
Dell:   30.47
HP: 33.91
IBM:    181.71
 
The current share price of HP is : 33.91
 
The size of the LinkedHashMap is : 5
 
Is LinkedHashMap empty? : false
 
LinkedHashMap contains Sony as key? : true
LinkedHashMap contains 999.0 as value? : false
 
Remove entry for Dell : 30.47
Content of LinkedHashMap removing Dell: {Apple=91.98, Sony=16.76, HP=33.91, IBM=181.71}
 
Content of LinkedHashMap after clearing: {}

3. Scenarios of using each implementation

If performance is critical but ordering is not, go for HashMap. If sorting is important, for example showing values in a table, sorted in alphabetical order then go for TreeMap. If a value is added in the TreeMap or removed from the TreeMap, TreeMap will make sure the table is still sorted alphabetically. If the order of insertion is important, for example showing values in a shopping cart, go for LinkedHashMap.

4. Download the source code

This was an example of how to use the class LinkedHashMap.

Download
Download the Eclipse project of this tutorial: Java LinkedHashMap Example

Last updated on Jun. 01st, 2020

Arpit Rathore

Arpit has graduated from the department of Computer science and Engineering of Pune University, India. He is currently working as a Software Engineer in the Health Care sector undertaking projects mostly based on Java. He has around 3 years of java development experience.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button