Java LinkedHashMap Tutorial with Examples

In this tutorial of Java language, we will learn one of the important Collection class – Java LinkedHashMap tutorial with examples.

Java LinkedHashMap class is widely used in Java programming language and it has many advantages and features.

Let’s get started :

Introduction to LinkedHashMap

LinkedHashMap class in Java is an implementation class for the Map interface and also a sub class for the HashMap class.

LinkedHashMap is basically a Hashtable and Doubly Linked list implementation of the Map interface.

LinkedHashMap class in Java is used to store key-value pairs similar to HashMap class of Java. It additionally provides predictable iteration order for its elements.

Hierarchy of Java LinkedHashMap

LinkedHashMap class extends the HashMap and implements the Map interface.

Java LinkedHashMap Tutorial with Examples

Need for LinkedHashMap

HashMap class in java doesn’t guarantee the iteration order for its elements. HashMap does not remember the order in which its elements were inserted and during iteration over its element, HashMap produces its elements in any random order.

LinkedHashMap is used in order of using a Map with predictable iteration over its elements.

LinkedHashMap generally provides its elements the order in which the elements were inserted i.e insertion order for its elements.

Still, we can change the iteration order from the least recently accessed element to the most recently accessed element and vice versa using the special constructor provided by LinkedHashMap.

Important Points about LinkedHashMap

Below points are most important to be remembered about Java LinkedHashMap :

  • LinkedHashMap in Java contains the values based on the key.
  • LinkedHashMap in Java can have only one null key and multiple null values.
  • LinkedHashMap in Java can only contain unique elements.
  • LinkedHashMap in Java maintains the insertion order for its elements.
  • LinkedHashMap is a non synchronized collection in Java.
  • The initial default capacity of Java HashMap class is 16 and a load factor is 0.75.

LinkedHashMap class Declaration

Below is the declaration of Java LinkedHashMap class as per Oracle :

Java LinkedHashMap Tutorial with Examples
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>

LinkedHashMap class Parameters

LinkedHashMap class parameters are listed below :

  • K: It represents the type of keys maintained by this map.
  • V: It represents the type of mapped values.

Constructors of Java LinkedHashMap class

ConstructorDescription
LinkedHashMap()This is a default constructor of LinkedHashMap class which is simply used to create a default LinkedHashMap.
LinkedHashMap(int capacity)This parameterized constructor is used to create a LinkedHashMap with the provided capacity.
LinkedHashMap(int capacity, float loadFactor)This parameterized constructor is used to create a LinkedHashMap with the provided capacity and the load factor.
LinkedHashMap(int capacity, float loadFactor, boolean accessOrder)This parameterized constructor is used to create a LinkedHashMap with the provided capacity and the load factor with the specified ordering mode.
LinkedHashMap(Map<? extends K,? extends V> m)This constructor is used to initialize the LinkedHashMap with the elements from the given Map class m.

Methods of Java LinkedHashMap class

MethodDescription
V get(Object key)This method is used to return the value to which the specified key is mapped.
void clear()This method removes all the key-value pairs from a map.
boolean containsValue(Object value)This method returns value true if the map maps one or more keys to the specified value.
Set<Map.Entry<K,V>> entrySet()This method is used to return a Set view of the mappings contained in the map.
void forEach(BiConsumer<? super K,? super V> action)This method is used to perform the given action for each entry in the map until all entries have been processed or the action throws an exception.
V getOrDefault(Object key, V defaultValue)This method is used to return the value to which the specified key is mapped or mentioned defaultValue if this map contains no mapping for the key.
Set<K> keySet()This method returns a Set view of the keys contained in the map
protected boolean removeEldestEntry(Map.Entry<K,V> eldest)This method is used to return value true on removing its eldest entry.
void replaceAll(BiFunction<? super K,? super V,? extends V> function)This method replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or when function throws an exception.
Collection<V> values()This method returns a Collection view of the values contained in this map.

Creating and Initializing a Java LinkedHashMap Example

The below example illustrates :

  • How to create a LinkedHashMap and
  • How to add new key-value pairs to LinkedHashMap.
import java.util.LinkedHashMap;

public class LinkedHashMapExample{

//Main method
    public static void main(String[] args) {

       // Creation of a LinkedHashMap 
        LinkedHashMap<Integer, String> friends = new LinkedHashMap<>();

       // Addition of new key-value pairs to the createdLinkedHashMap
        friends.put(1, "Ross");
        friends.put(2, "Rachel");
        friends.put(3, "Phoebe");
        friends.put(4, "Chandler");
        friends.put(5, "Joey");
        friends.put(6, "Monica");

       // Addition of a new key-value pair like below will only work 
       // if the key does not exist in the LinkedHashMap, or is mapped to `null`
        friends.putIfAbsent(5, "Janice");

        System.out.println(friends);
    }
}

Output :

{1=Ross, 2=Rachel, 3=Phoebe, 4=Chandler, 5=Joey, 6=Monica}

Accessing the entries of a Java LinkedHashMap Example

The below example illustrates :

  • How to check if a key exists in a LinkedHashMap or not.
  • How to check if a value exists in the LinkedHashMap or not.
  • How to modify the value associated with a given key in the LinkedHashMap.
import java.util.LinkedHashMap;

public class LinkedHashMapExample {
    
//Main method
    public static void main(String[] args) {
        
        //Creating the LinkedHashMap
        LinkedHashMap<Integer, String> students = new LinkedHashMap<>();
        
        
        //Adding values to the LinkedHashMap
        students.put(1, "Penny");
        students.put(2, "Sheldon");
        students.put(3, "Leonard");
        students.put(4, "Raj");
        students.put(5, "Howard");
        
        //Printing the LinkedHashMap
        System.out.println("Students : " + students);

        //Checking if the mentioned key exists in the LinkedHashMap or not
        
        Integer id = 4;
        
        if(students.containsKey(id)) {
            System.out.println("Found the Student with id number " + id + " : " + students.get(id));
        } else {
            System.out.println("Student with id number " + id + " does not exist");
        }

        //Checking if a value exists in the LinkedHashMap or not
        
        String name = "Wolowitz";
        
        if(students.containsValue(name)) {
            System.out.println("A Student named " + name + " exist in the map");
        } else {
            System.out.println("No Student found with name " + name + " in the map");
        }

        //Changing the value associated with an existing key in LinkedHashMap
        id = 4;
        students.put(id, "Rajesh");
        System.out.println("Changed the name of student with id number " + id + ", New mapping : " + students);
    }
}

Output :

Students : {1=Penny, 2=Sheldon, 3=Leonard, 4=Raj, 5=Howard} 
Found the Student with id number 4 : Raj 
No Student found with name Wolowitz in the map 
Changed the name of student with id number 4, New mapping : {1=Penny, 2=Sheldon, 3=Leonard, 4=Rajesh, 5=Howard} 

Removing the entries from a Java LinkedHashMap Example

The below example illustrates :

  • How to remove a key from a LinkedHashMap in Java.
  • How to remove a key from a LinkedHashMap only if it is associated with the given value.
import java.util.LinkedHashMap;

public class LinkedHashMapExample {
    
//Main method
    public static void main(String[] args) {
        
        //Creating the LinkedHashMap
        LinkedHashMap<Integer, String> favShows = new LinkedHashMap<>();
        
        
        //Adding values to the LinkedHashMap
        favShows.put(1, "BigBangTheory");
        favShows.put(2, "Friends");
        favShows.put(3, "TwoAndAHalfMen");

        
        //Printing the LinkedHashMap
        System.out.println("Fav Shows : " + favShows);

        //Removing a key from the LinkedHashMap
        String name = favShows.remove(3);
        System.out.println("Removed the " + name  + " from the mapping. New List  : " + favShows);

        //Removing a key from the LinkedHashMap only if it is mapped to the given value
        boolean isRemoved = favShows.remove(1, "MindyPoject");
        System.out.println("Did MindyPoject get removed from the mapping? : " + isRemoved);
    }
}

Output :

Fav Shows : {1=BigBangTheory, 2=Friends, 3=TwoAndAHalfMen} 
Removed the TwoAndAHalfMen from the mapping. 
New List  : {1=BigBangTheory, 2=Friends} 
Did MindyPoject get removed from the mapping? : false 

Iterating over a Java LinkedHashMap Example

The below example illustrates :

  • How to iterate over a LinkedHashMap using Java 8 forEach and lambda expression.
  • How to Iterate over a LinkedHashMap’s entrySet using iterator().
  • How to Iterate over a LinkedHashMap’s entrySet using iterator() and Java 8 forEachRemaining() method.
  • How to Iterate over a LinkedHashMap’s entrySet using Java 8 forEach and lambda expression.
import java.util.*;

public class LinkedHashMapExample {
    
//Main method
    public static void main(String[] args) {
        
        //Creating the LinkedHashMap
        LinkedHashMap<Integer, String> favShows = new LinkedHashMap<>();
        
        
        //Adding values to the LinkedHashMap
        favShows.put(1, "Big Bang Theory");
        favShows.put(2, "Friends");
        favShows.put(3, "Two And A Half Men");
        favShows.put(4, "Mindy Project");

        
        System.out.println("*** Iterate over a LinkedHashMap using Java 8 forEach and lambda ***\n");
        
        favShows.forEach((number, name) -> {
            System.out.println(number + " => " + name);
        });

        System.out.println("*** Iterate over a LinkedHashMap's entrySet using Java 8 forEach and lambda ***\n");
        
        favShows.entrySet().forEach(entry -> {
            System.out.println(entry.getKey() + " => " + entry.getValue());
        });

        System.out.println("*** Iterate over the entrySet of a LinkedHashMap using iterator() ***\n");
        
        Iterator<Map.Entry<Integer, String>> favShowsIterator = favShows.entrySet().iterator();
        
        while (favShowsIterator.hasNext()) {
            
            Map.Entry<Integer, String> entry = favShowsIterator.next();
            
            System.out.println(entry.getKey() + " => " + entry.getValue());
        }

        System.out.println("*** Iterate over the entrySet of a LinkedHashMap using iterator() and forEachRemaining ***\n");
        
        favShowsIterator = favShows.entrySet().iterator();
        
        favShowsIterator.forEachRemaining(entry -> {
            System.out.println(entry.getKey() + " => " + entry.getValue());
        });
    }
}

Output :

*** Iterate over a LinkedHashMap using Java 8 forEach and lambda ***

1 => Big Bang Theory
2 => Friends
3 => Two And A Half Men
4 => Mindy Project

*** Iterate over a LinkedHashMap's entrySet using Java 8 forEach and lambda ***

1 => Big Bang Theory
2 => Friends
3 => Two And A Half Men
4 => Mindy Project

*** Iterate over the entrySet of a LinkedHashMap using iterator() ***

1 => Big Bang Theory
2 => Friends
3 => Two And A Half Men
4 => Mindy Project

*** Iterate over the entrySet of a LinkedHashMap using iterator() and forEachRemaining ***

1 => Big Bang Theory
2 => Friends
3 => Two And A Half Men
4 => Mindy Project

HashMap vs LinkedHashMap

Java LinkedHashMap Tutorial with Examples

Java LinkedHashMap Use Cases

Java LinkedHashMap can be used in almost every scenarios wherever HashMap is required like storing elements as key-value pair.

We can say LinkedHashMap can replace HashMap functionality wise.

However, Java LinkedHashMap maintains insertion order for its elements thus it is mainly useful for storing the elements which are in key-value pairs and the ordering is also important for the elements.

Java LinkedHashMap can be used for creating the LRU Cache because of its access order.

Java LinkedHashMap Performance

Java LinkedHashMap and HashMap both provides constant time performance for the operations like adding, removing and checking if map contains a element.

However, Java LinkedHashMap performance is little worse than the HashMap. As LinkedHashMap uses Doubly LinkedList and HashMap only uses LinkedList.

At the same time, Java LinkedHashMap performs better than HashMap in case of looping through the Map as the time required is proportional to ‘size’ only.

Iteration performance for HashMap is proportional to ‘size + capacity’.

Concurrency in Java LinkedHashMap

Java LinkedHashMap and HashMap both are non synchronized i.e. not thread safe.

We can use HashMap and LinkedHashMap both directly in multithreaded environment.

As they are non – synchronized, we need to explicitly synchronize them by using Collections.synchronizedMap(Map map) method.

Map<Integer, Integer> data = Collections.synchronizedMap(new LinkedHashMap<>());
 
Map<Integer, Integer> data = Collections.synchronizedMap(new HashMap<>());

ConcurrentHashMap  is recommended in case of HashMap as it provides higher degree of concurrency.

Conclusion

In this article of Java LinkedHashMap Tutorial with Examples, we have learnt the LinkedHashMap class of Java Collections framework with its features, its examples etc.

We have also learnt, How to create LinkedHashMap and How to iterate over Java LinkedHashMap and many more examples.

Leave a Reply

Your email address will not be published. Required fields are marked *