Home » Java Tutorial » LinkedHashMap in Java

LinkedHashMap in Java




Java Java Map

LinkedHashMap class in Java is a LinkedList implementation that is similar to a HashMap but preserves the insertion order. It extends the HashMap class and implements the Map interface. It uses the doubly LinkedList implementation to iterate through all the nodes in the LinkedHashMap.

Features of LinkedHashMap

  • It maintains the order of the entries in the same way it inserts the elements.
  • LinkedHashMap can contain only unique data
  • Can have only one null key but multiple null values.

Constructors in LinkedHashMap

Below are the constructors present in the LinkedHashMap class.

ConstructorDescription
LinkedHashMap()Initializes a default LinkedHashMap
LinkedHashMap(Map m)Initializes the LinkedHashmap with elements of Map m
LinkedHashMap(int capacity)Initializes the Linkedhashmap with the specified capacity integer value
LinkedHashMap(int capacity, float loadfactor)Initializes the Linkedhashmap with the specified capacity and load factor
LinkedHashMap(int capacity, float loadFactor, boolean accessOrder)Initializes the LinkedhashMap with the specified capacity and load factor along with the access order mode

Methods of LinkedHashMap in Java

MethodDescriptionParameter
void clear()Removes all the mappings in this map which means map will be empty
Object clone()Returns a shallow copy of this HashMap instance. Key and values themselves are not cloned
Boolean containsKey(Object key)Returns true if there is a mapping value for the specified keykey - the key for which we need to retrieve the value
Boolean containsValue(Object value)Returns true if there is mapping of key for the specified valuevalue - the value for which specified key is mapped
Set<Entry> entrySet()Returns a set view of the mapping of the map
Boolean equals(Object o)Returns true if the object has the same mapping of the mapo - the object to be compared
Integer get(Object key)Returns the value of the specified key in the map. It returns null if there is no mappingkey - the key for which value mapping has to be retrieved
Integer getOrDefault(Object key, Integer defaultvalue)Returns the value of the specified key if mapped, else returns the defaultvalue if there is no mappingkey - the key for which we value has to be returned
defaultvalue - the default value to be returned when there is no mapping
int hashCode()Returns the hashcode value of the map
Boolean isEmpty()Returns true is the hashmap does not have any key-value pairs
Set keySet()Returns the set view of the keys present in the map
Integer put(String key, int value)Associates the key with value. If the key is already present, it replaces the old value with new valuekey - key for mapping
value - value for the specified key
void putAll(Map m)Associates all key - value mappings of m to the current mapm - the copies of the mapping to be added to the current map
Integer putIfAbsent(String key,Integer value)Associates the value if already not mapped to the key else returns the current valuekey - key for mapping
value - value to be associated
Integer remove(Object key)Removes the mapping for the specified key in the mapkey - the key in the map for which mapping has to be removed
Boolean remove(Object key, Object value)Removes the entry of the specified key only if it is mapped with the specified valuekey - key in map
value - value mapped to the key
Integer replace(String key, Integer value)Replaces the value of the specified key with the value only if it currently mapped with some valuekey - key in map
value - value to be replaced
Boolean replace(String key, integer oldvalue, Integer newvalue)Replaces the entry of the specified key with new value only if it already mapped with the specified oldvaluekey - key in the map
oldvalue - oldvalue mapped to key
newvalue - newvalue to be mapped to the key
int size()Returns the size of the map
String toString()Returns a string representation of the map
Collection values()Returns a collection view of values present in the map
READ  Java Substring

Working of LinkedHashMap in Java

LinkedHashMap in Java works on the implementation of the doubly linked list which means it contains addresses of the next element and the previous element. In this way, it also maintains the insertion order.

In the below diagram, prev denotes the address of the previous element and next denotes the address of the next element.

LinkedHashMap in Java

Example: Adding elements to the LinkedHashMap

Below is an example of adding elements to the LinkedHashMap. We can see that it maintains the insertion order and displays the elements in the same order as we have inserted it. But this functionality is not present in the HashMap which is the major difference.

import java.util.LinkedHashMap;

public class AddElements {

  public static void main(String[] args) {
    LinkedHashMap<Integer,String> lh = new LinkedHashMap<Integer,String>();
    lh.put(1, "Aarthi");
    lh.put(2, "Bahrathi");
    lh.put(3, "Chandini");
    
    System.out.println("Elements in the LinkedHashMap: " + lh);
    
    LinkedHashMap<Integer,String> lhm = new LinkedHashMap<Integer,String>();
    lhm.put(4, "Devi");
    lhm.put(5, "Fathima");
    
    lh.putAll(lhm);
    
    System.out.println("Elements in the LinkedHashMap after adding Map elements: " + lh);
    

  }

}
Elements in the LinkedHashMap: {1=Aarthi, 2=Bahrathi, 3=Chandini}
Elements in the LinkedHashMap after adding Map elements: {1=Aarthi, 2=Bahrathi, 3=Chandini, 4=Devi, 5=Fathima}

Example: Update elements in the LinkedHashMap

Using the put() method, we can replace the value of the existing key if present. In the below example, we are replacing the value of key “2”. Since this key is already present, it will replace the old value with the new value, else it will add as a new element.

import java.util.LinkedHashMap;

public class AddElements {

  public static void main(String[] args) {
    LinkedHashMap<Integer,String> lh = new LinkedHashMap<Integer,String>();
    lh.put(1, "Aarthi");
    lh.put(2, "Bharathi");
    lh.put(3, "Chandini");
    
    System.out.println("Elements in the LinkedHashMap: " + lh);
    
    //Update value
    lh.put(2, "Sarika");
    
    System.out.println("Elements in the LinkedHashMap after updating the second element: " + lh);
    

  }

}
Elements in the LinkedHashMap: {1=Aarthi, 2=Bharathi, 3=Chandini}
Elements in the LinkedHashMap after updating the second element: {1=Aarthi, 2=Sarika, 3=Chandini}

We can also update the values using the replace() method.

import java.util.LinkedHashMap;

public class AddElements {

  public static void main(String[] args) {
    LinkedHashMap<Integer,String> lh = new LinkedHashMap<Integer,String>();
    lh.put(1, "Aarthi");
    lh.put(2, "Bharathi");
    lh.put(3, "Chandini");
    
    System.out.println("Elements in the LinkedHashMap: " + lh);
    
    lh.replace(3, "Chandru");
    lh.replace(1, "Aarthi", "Akash");
    
    System.out.println("Elements in the LinkedHashMap after using the replace method: " + lh);
    

  }

}
Elements in the LinkedHashMap: {1=Aarthi, 2=Bharathi, 3=Chandini}
Elements in the LinkedHashMap after using the replace method: {1=Akash, 2=Bharathi, 3=Chandru}

Example: Remove elements from the LinkedHashMap in Java

We can remove or delete the elements from the LinkedHashMap in Java using the remove() method. To remove all the elements in the LinkedHashMap, we can use the clear() method. We can check if the map is empty using the isEmpty() method.

import java.util.LinkedHashMap;

public class RemoveElements {

  public static void main(String[] args) {
    LinkedHashMap<Integer,String> lh = new LinkedHashMap<Integer,String>();
    lh.put(1, "Aarthi");
    lh.put(2, "Bahrathi");
    lh.put(3, "Chandini");
    
    System.out.println("Elements in the LinkedHashMap: " + lh);
    
    lh.remove(2);
    System.out.println("Elements in the LinkedHashMap after removing the 2nd element: " + lh);
    
    lh.remove(1, "Aarthi");
    System.out.println("Elements in the LinkedHashMap after removing the 1st element: " + lh);
    
    lh.clear();
    System.out.println("Is LinkedHashMap empty: " + lh.isEmpty());

  }

}
Elements in the LinkedHashMap: {1=Aarthi, 2=Bahrathi, 3=Chandini}
Elements in the LinkedHashMap after removing the 2nd element: {1=Aarthi, 3=Chandini}
Elements in the LinkedHashMap after removing the 1st element: {3=Chandini}
Is LinkedHashMap empty: true

Example: Iterate through LinkedHashMap elements in Java

To retrieve all the elements in the form of key-value pairs from the LinkedHashMap, we can use the entrySet() method. Using the  Map.Entry instance, we can individually get the key data using the getKey() and value using the getValue() method.

READ  Java List

We can retrieve all the key data from the map using the keySet() method and all the values using the values() method.

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class IterateLinkedHashMap {

  public static void main(String[] args) {
    LinkedHashMap<Integer,String> lh = new LinkedHashMap<Integer,String>();
    lh.put(1, "Aarthi");
    lh.put(2, "Bharathi");
    lh.put(3, "Chandini");
    
    System.out.println("Iterate using EntrySet method: ");
    for(Map.Entry<Integer, String> m : lh.entrySet()) {
      System.out.println(m.getKey() + " : " + m.getValue());
    }
    
    System.out.println("Iterate using the KeySet method: ");
    for(Integer s : lh.keySet()) {
      System.out.println(s);
    }
    
    System.out.println("Iterate using the Collection values method: ");
    for(String val : lh.values()) {
      System.out.println(val);
    }
      
      

  }

}
Iterate using EntrySet method: 
1 : Aarthi
2 : Bharathi
3 : Chandini
Iterate using the KeySet method: 
1
2
3
Iterate using the Collection values method: 
Aarthi
Bharathi
Chandini

Example: Retrieve values based on the key

Below is the example of retrieving a specific key value using the get() method. We can print the default value if a specific key is not present using the getOrDefault() method.

We can also check if the map contains a specific key or value using the containsKey() or containsValue() method.

import java.util.LinkedHashMap;

public class RetrieveData {

  public static void main(String[] args) {
    LinkedHashMap<Integer,String> lh = new LinkedHashMap<Integer,String>();
    lh.put(1, "Aarthi");
    lh.put(2, "Bharathi");
    lh.put(3, "Chandini");
    
    System.out.println("Value of Key 2: " + lh.get(2));
    System.out.println("Value of Key 3 if present: " + lh.getOrDefault(3, "Test"));
    System.out.println("Value of key when not present: " + lh.getOrDefault(4, "Test"));
    
    System.out.println("Does key 1 exist: " + lh.containsKey(1));
    System.out.println("Does value exist: " + lh.containsValue("Chandini"));
    System.out.println("Doe key 4 exist: " + lh.containsKey(4));
    System.out.println("Does value exist: " + lh.containsValue("Test"));
    

  }

}
Value of Key 2: Bharathi
Value of Key 3 if present: Chandini
Value of key when not present: Test
Does key 1 exist: true
Does value exist: true
Doe key 4 exist: false
Does value exist: false

Reference

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions
Core Java Interview Questions

AD Blocker Detected !

Advertisements help running this website for free.

To view the content please disable AdBlocker and refresh the page.

Wait !!!

You can Crack Technical Interviews of Companies like Amazon, Google, LinkedIn, Facebook, PayPal, Flipkart, etc

Abhishek

Abhishek was able to crack Microsoft after practicing questions from TutorialCup