The Wayback Machine - https://web.archive.org/web/20240926155034/https://www.geeksforgeeks.org/linkedhashmap-class-in-java/
Open In App

LinkedHashMap in Java

Last Updated : 01 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Let us start with a simple Java code snippet that demonstrates how to create and use a LinkedHashMap in Java.

Java
import java.util.LinkedHashMap;

public class LinkedHashMapCreation {
    public static void main(String[] args) {
        
        // Create a LinkedHashMap of Strings (keys) and Integers (values)
        LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>();
        
        // Displaying the LinkedHashMap
        System.out.println("LinkedHashMap Elements: " + linkedHashMap);
    }
}

Output
LinkedHashMap Elements: {}

The LinkedHashMap Class is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but it never maintained the track and order of insertion, which the LinkedHashMap provides where the elements can be accessed in their insertion order. 

Features of a LinkedHashMap:

  • A LinkedHashMap contains values based on the key. It implements the Map interface and extends the HashMap class.
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • It is non-synchronized.
  • It is the same as HashMap with an additional feature that it maintains insertion order. For example, when we run the code with a HashMap, we get a different order of elements.

Declaration of LinkedHashMap:

public class LinkedHashMap<K,​V> extends HashMap<K,​V> implements Map<K,​V>

Here, K is the key Object type and V is the value Object type

  • K: The type of the keys in the map.
  • V: The type of values mapped in the map.

How LinkedHashMap Work Internally?

A LinkedHashMap is an extension of the HashMap class and it implements the Map interface. Therefore, the class is declared as:

public class LinkedHashMap 
extends HashMap
implements Map 

In this class, the data is stored in the form of nodes. The implementation of the LinkedHashMap is very similar to a doubly-linked list. Therefore, each node of the LinkedHashMap is represented as:

LinkedHashMap Node Representation inJava

  • Hash: All the input keys are converted into a hash which is a shorter form of the key so that the search and insertion are faster.
  • Key: Since this class extends HashMap, the data is stored in the form of a key-value pair. Therefore, this parameter is the key to the data.
  • Value: For every key, there is a value associated with it. This parameter stores the value of the keys. Due to generics, this value can be of any form.
  • Next: Since the LinkedHashMap stores the insertion order, this contains the address to the next node of the LinkedHashMap.
  • Previous: This parameter contains the address to the previous node of the LinkedHashMap.

Synchronized LinkedHashMap

The implementation of LinkedHashMap is not synchronized. If multiple threads access a linked hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be “wrapped” using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

Map m = Collections.synchronizedMap(new LinkedHashMap(...));

Constructors of LinkedHashMap Class

In order to create a LinkedHashMap, we need to create an object of the LinkedHashMap class. The LinkedHashMap class consists of various constructors that allow the possible creation of the ArrayList. The following are the constructors available in this class:

1. LinkedHashMap(): This is used to construct a default LinkedHashMap constructor.

LinkedHashMap<K, V> lhm = new LinkedHashMap<K, V>();


2. LinkedHashMap(int capacity): It is used to initialize a particular LinkedHashMap with a specified capacity.

LinkedHashMap<K, V> lhm = new LinkedHashMap<K, V>(int capacity);


3. LinkedHashMap(Map<? extends K,​? extends V> map): It is used to initialize a particular LinkedHashMap with the elements of the specified map.

LinkedHashMap<K, V> lhm = new LinkedHashMap<K, V>(Map<? extends K,​? extends V> map);


4. LinkedHashMap(int capacity, float fillRatio): It is used to initialize both the capacity and fill ratio for a LinkedHashMap. A fillRatio also called as loadFactor is a metric that determines when to increase the size of the LinkedHashMap automatically. By default, this value is 0.75 which means that the size of the map is increased when the map is 75% full.

LinkedHashMap<K, V> lhm = new LinkedHashMap<K, V>(int capacity, float fillRatio);


5. LinkedHashMap(int capacity, float fillRatio, boolean Order): This constructor is also used to initialize both the capacity and fill ratio for a LinkedHashMap along with whether to follow the insertion order or not.

LinkedHashMap<K, V> lhm = new LinkedHashMap<K, V>(int capacity, float fillRatio, boolean Order);

Here, For the Order attribute, true is passed for the last access order and false is passed for the insertion order.

Methods of LinkedHashMap 

Method

Description

containsValue​(Object value)Returns true if this map maps one or more keys to the specified value.
entrySet()Returns a Set view of the mappings contained in this map.
get​(Object key)Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
keySet()Returns a Set view of the keys contained in this map.
removeEldestEntry​(Map.Entry<K,​V> eldest)Returns true if this map should remove its eldest entry.
values()Returns a Collection view of the values contained in this map.

Application: Since the LinkedHashMap makes use of Doubly LinkedList to maintain the insertion order, we can implement LRU Cache functionality by overriding the removeEldestEntry() method to impose a policy for automatically removing stale when new mappings are added to the map. This lets you expire data using some criteria that you define.

Example:

Java
// Java Program to Demonstrate Working of LinkedHashMap

// Importing required classes
import java.util.*;

// LinkedHashMapExample
public class GFG {

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

        // Creating an empty LinkedHashMap
        LinkedHashMap<String, String> lhm
            = new LinkedHashMap<String, String>();

        // Adding entries in Map
        // using put() method
        lhm.put("one", "practice.geeksforgeeks.org");
        lhm.put("two", "code.geeksforgeeks.org");
        lhm.put("four", "www.geeksforgeeks.org");

        // Printing all entries inside Map
        System.out.println(lhm);

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

        // Getting and printing value for a specific key
        System.out.println("Getting value for key 'one': "
                           + lhm.get("one"));

        // Getting size of Map using size() method
        System.out.println("Size of the map: "
                           + lhm.size());

        // Checking whether Map is empty or not
        System.out.println("Is map empty? "
                           + lhm.isEmpty());

        // Using containsKey() method to check for a key
        System.out.println("Contains key 'two'? "
                           + lhm.containsKey("two"));

        // Using containsKey() method to check for a value
        System.out.println(
            "Contains value 'practice.geeks"
            + "forgeeks.org'? "
            + lhm.containsValue("practice"
                                + ".geeksforgeeks.org"));

        // Removing entry using remove() method
        System.out.println("delete element 'one': "
                           + lhm.remove("one"));

        // Printing mappings to the console
        System.out.println("Mappings of LinkedHashMap : "
                           + lhm);
    }
}

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

Various operations on the LinkedHashMap class

Let’s see how to perform a few frequently used operations on the LinkedHashMap class instance.

Operation 1: Adding Elements

In order to add an element to the LinkedHashMap, we can use the put() method. This is different from HashMap because in HashMap, the insertion order is not retained but it is retained in the LinkedHashMap. 

Example:

Java
// Java Program to Demonstrate Adding
// Elements to a LinkedHashMap

// Importing required classes
import java.util.*;

// Main class
// AddElementsToLinkedHashMap
class GFG {

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

        // Initialization of a LinkedHashMap
        // using Generics
        LinkedHashMap<Integer, String> hm1
            = new LinkedHashMap<Integer, String>();

        // Add mappings to Map
        // using put() method
        hm1.put(3, "Geeks");
        hm1.put(2, "For");
        hm1.put(1, "Geeks");

        // Printing mappings to the console
        System.out.println("Mappings of LinkedHashMap : "
                           + hm1);
    }
}

Output
Mappings of LinkedHashMap : {3=Geeks, 2=For, 1=Geeks}


Operation 2: Changing/Updating Elements

After adding elements if we wish to change the element, it can be done by again adding the element using the put() method. Since the elements in the LinkedHashMap are indexed using the keys, the value of the key can be changed by simply re-inserting the updated value for the key for which we wish to change.

Example:

Java
// Java Program to Demonstrate Updation of Elements
// of LinkedHashMap

import java.util.*;

// Main class
// UpdatingLinkedHashMap
class GFG {

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

        // Initialization of a LinkedHashMap
        // using Generics
        LinkedHashMap<Integer, String> hm
            = new LinkedHashMap<Integer, String>();

        // Inserting mappings into Map
        // using put() method
        hm.put(3, "Geeks");
        hm.put(2, "Geeks");
        hm.put(1, "Geeks");

        // Printing mappings to the console
        System.out.println("Initial map : " + hm);

        // Updating the value with key 2
        hm.put(2, "For");

        // Printing the updated Map
        System.out.println("Updated Map : " + hm);
    }
}

Output
Initial map : {3=Geeks, 2=Geeks, 1=Geeks}
Updated Map : {3=Geeks, 2=For, 1=Geeks}


Operation 3: Removing Element

In order to remove an element from the LinkedHashMap, we can use the remove() method. This method takes the value of key as input, searches for existence of such key and then removes the mapping for the key from this LinkedHashMap if it is present in the map. Apart from that, we can also remove the first entered element from the map if the maximum size is defined.

Example:

Java
// Java program to Demonstrate Removal of Elements
// from LinkedHashMap

// Importing utility classes
import java.util.*;

// Main class
// RemovingMappingsFromLinkedHashMap
class GFG {

    // Main driver method
    public static void main(String args[])
    {
        // Initialization of a LinkedHashMap
        // using Generics
        LinkedHashMap<Integer, String> hm
            = new LinkedHashMap<Integer, String>();

        // Inserting the Elements
        // using put() method
        hm.put(3, "Geeks");
        hm.put(2, "Geeks");
        hm.put(1, "Geeks");
        hm.put(4, "For");

        // Printing the mappings to the console
        System.out.println("Initial Map : " + hm);

        // Removing the mapping with Key 4
        hm.remove(4);

        // Printing the updated map
        System.out.println("Updated Map : " + hm);
    }
}

Output
Initial Map : {3=Geeks, 2=Geeks, 1=Geeks, 4=For}
Updated Map : {3=Geeks, 2=Geeks, 1=Geeks}

 

Operation 4: Iterating through the LinkedHashMap

There are multiple ways to iterate through the LinkedHashMap. The most famous way is to use a for-each loop over the set view of the map (fetched using map.entrySet() instance method). Then for each entry (set element) the values of key and value can be fetched usingthe getKey() and the getValue() method.

Example:

Java
// Java program to demonstrate
// Iterating over LinkedHashMap

// Importing required classes
import java.util.*;

// Main class
// IteratingOverLinkedHashMap
class GFG {

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

        // Initialization of a LinkedHashMap
        // using Generics
        LinkedHashMap<Integer, String> hm
            = new LinkedHashMap<Integer, String>();

        // Inserting elements into Map
        // using put() method
        hm.put(3, "Geeks");
        hm.put(2, "For");
        hm.put(1, "Geeks");

        // For-each loop for traversal over Map
        for (Map.Entry<Integer, String> mapElement :
             hm.entrySet()) {

            Integer key = mapElement.getKey();

            // Finding the value
            // using getValue() method
            String value = mapElement.getValue();

            // Printing the key-value pairs
            System.out.println(key + " : " + value);
        }
    }
}

Output
3 : Geeks
2 : For
1 : Geeks

Related Articles: 



Previous Article
Next Article

Similar Reads

LinkedHashMap containsKey() Method in Java with Examples
The java.util.LinkedHashMap.containsKey() method is used to check whether a particular key is being mapped into the LinkedHashMap or not. It takes the key element as a parameter and returns True if that element is mapped in the map.Syntax: Linked_Hash_Map.containsKey(key_element) Parameters: The method takes just one parameter key_element that refe
2 min read
LinkedHashMap clear() Method in Java
The java.util.LinkedHashMap.clear() is an inbuilt method of LinkedHashMap class in Java and is used to clear all the elements or the mappings from the denoted LinkedHashMap. The map will become empty after the operation is performed. Syntax: Linked_Hash_Map.clear() Parameters: The method does not take any parameters. Return Value: The method does n
2 min read
LinkedHashMap get() Method in Java with Examples
In Java, get() method of LinkedHashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key. --&gt; java.util Package --&gt; LinkedHashMap Class --&gt; get() Method Syntax: Linked_Hash_Map.get(Object key_element) Parameter: One parameter
2 min read
LinkedHashMap removeEldestEntry() Method in Java
The java.util.LinkedHashMap.removeEldestEntry() method in Java is used keep a track of whether the map removes any eldest entry from the map. So each time a new element is added to the LinkedHashMap, the eldest entry is removed from the map. This method is generally invoked after the addition of the elements into the map by the use of put() and put
3 min read
LinkedHashMap and LinkedHashSet in Java
The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but it never maintained the track and order of insertion which the LinkedHashMap provides where the elements can be accessed in their insertion order. Example
3 min read
Print characters and their frequencies in order of occurrence using a LinkedHashMap in Java
Given a string str containing only lowercase characters. The task is to print the characters along with their frequencies in the order of their occurrence in the given string.Examples: Input: str = "geeksforgeeks" Output: g2 e4 k2 s2 f1 o1 r1Input: str = "helloworld" Output: h1 e1 l3 o2 w1 r1 d1 Approach: Traverse the given string character by char
2 min read
Differences between TreeMap, HashMap and LinkedHashMap in Java
Prerequisite : HashMap and TreeMap in Java TreeMap, HashMap and LinkedHashMap: What's Similar? All offer a key-&gt;value map and a way to iterate through the keys. The most important distinction between these classes is the time guarantees and the ordering of the keys.All three classes HashMap, TreeMap and LinkedHashMap implements java.util.Map int
5 min read
Maven Project - LinkedHashMap and LinkedHashSet usage Along with JUnit Testing
In software programming, there are many instances where we need the usage of LinkedHashMap and LinkedHashSet. LinkedHashSet Though HashSet is available, if we need the ordered version of HashSet, we need the LinkedHashSet. The advantage is when we iterate the LinkedHashSet, we get the display of the elements in the inserted order. Because of the ex
7 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
java.lang.Math.atan2() in Java
atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between -[Tex]\pi [/Tex]and [Tex]\pi [/Tex]representing the angle [Tex]\theta [/Tex]of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positiv
1 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java Swing | Translucent and shaped Window in Java
Java provides different functions by which we can control the translucency of the window or the frame. To control the opacity of the frame must not be decorated. Opacity of a frame is the measure of the translucency of the frame or component. In Java, we can create shaped windows by two ways first by using the AWTUtilities which is a part of com.su
5 min read
Java lang.Long.numberOfTrailingZeros() method in Java with Examples
java.lang.Long.numberOfTrailingZeros() is a built-in function in Java which returns the number of trailing zero bits to the right of the lowest order set bit. In simple terms, it returns the (position-1) where position refers to the first set bit from the right. If the number does not contain any set bit(in other words, if the number is zero), it r
3 min read
Java lang.Long.numberOfLeadingZeros() method in Java with Examples
java.lang.Long.numberOfLeadingZeros() is a built-in function in Java which returns the number of leading zero bits to the left of the highest order set bit. In simple terms, it returns the (64-position) where position refers to the highest order set bit from the right. If the number does not contain any set bit(in other words, if the number is zero
3 min read
Java lang.Long.highestOneBit() method in Java with Examples
java.lang.Long.highestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for the first set bit from the left, then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(last set bit position from
3 min read
Java lang.Long.byteValue() method in Java with Examples
java.lang.Long.byteValue() is a built-in function in Java that returns the value of this Long as a byte. Syntax: public byte byteValue() Parameters: The function does not accept any parameter. Return : This method returns the numeric value represented by this object after conversion to byte type. Examples: Input : 12 Output : 12 Input : 1023 Output
3 min read
Java lang.Long.reverse() method in Java with Examples
java.lang.Long.reverse() is a built-in function in Java which returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified long value. Syntax: public static long reverse(long num) Parameter : num - the number passed Returns : the value obtained by reversing the order of the bits in the
2 min read
java.lang.reflect.Proxy Class in Java
A proxy class is present in java.lang package. A proxy class has certain methods which are used for creating dynamic proxy classes and instances, and all the classes created by those methods act as subclasses for this proxy class. Class declaration: public class Proxy extends Object implements SerializableFields: protected InvocationHandler hIt han
4 min read
Java.math.BigInteger.modInverse() method in Java
Prerequisite : BigInteger Basics The modInverse() method returns modular multiplicative inverse of this, mod m. This method throws an ArithmeticException if m &lt;= 0 or this has no multiplicative inverse mod m (i.e., gcd(this, m) != 1). Syntax: public BigInteger modInverse(BigInteger m) Parameters: m - the modulus. Return Value: This method return
2 min read
Java.math.BigInteger.probablePrime() method in Java
Prerequisite : BigInteger Basics The probablePrime() method will return a Biginteger of bitLength bits which is prime. bitLength is provided as parameter to method probablePrime() and method will return a prime BigInteger of bitLength bits. The probability that a BigInteger returned by this method is composite and does not exceed 2^-100. Syntax: pu
2 min read