LinkedHashMap in java

LinkedHashMap is a Hashtable and linked list-based implementation of Map interface, with predictable insertion order. It maintains double linked list of all its entries, that’s how it differs from HashMap.

Java LinkedHashMap

Some points about LinkedHashMap

  1. LinkedHashMap implements Map interface and extends HashMap class.
  2. LinkedHashMap maintains insertion order, so when you will be able to access elements in the order they were inserted like ArrayList.
  3. LinkedHashMap maintains doubly Linked list to maintain insertion order.
  4. It is not synchronized and is not thread-safe.
  5. Duplicate keys are not allowed
  6. One null key and multiple null values are allowed

LinkedHashMap

Did you notice LinkedHashMap implements Map interface even if AbstractMap and HashMap already implements it?
Yes, Just to make things more obvious, LinkedHashMap implements Map interface again and there is nothing wrong in implementing interface again. You don’t have to go through class Hierarchy to find it out that LinkedHashMap implements Map interface.

LinkedHashMap Constructors

Java LinkedHashMap class has five constructors
public LinkedHashMap(): This is the default constructor and used mostly. It creates an empty LinkedHashMap with default initial capacity of 16 and load factor 0.75.
public LinkedHashMap(int initialCapacity): This constructor is used to specify the initial capacity of LinkedHashMap and default load factor 0.75.
public LinkedHashMap(int initialCapacity,float loadFactor): This constructor is used to specify initial capacity of the LinkedHashMap and load factor. In most of the scenarios, you should avoid using this constructor unless you are sure about this as load factor 0.75 provides a good tradeoff between time and space.
public LinkedHashMap(Map<? extends K,? extends V> m): This constructor is used when you want to create LinkedHashMap from some other Map such as TreeMap or HashMap.
public LinkedHashMap(int initialCapacity,float loadFactor,boolean accessOrder): This constructor is used to specify initial capacity, load factor and access order of HashMap. If we pass access order as true, then it will list entries based on access order.

Add key-value pairs to LinkedHashMap

We can use put() method to add entries to LinkedHashMap similar to HashMap.
Example:

When you run above program, you will get below output

{1=Arvind, 2=Andy, 3=Mohan, 4=Virat}

As you can see, all the entries are printed in insertion order as expected.
What if you want to add entries only if it is not already present in LinkedHashMap?
You can use putIfAbsent() the method in this scenario.

💡 Did you know?

After Java 7, you can use diamond operator(<>) to initialize Map.
You can change
Map<Integer, String> studentMap = new LinkedHashMap<Integer, String>(); to
Map<Integer, String> studentMap = new LinkedHashMap<>();

Remove entries from LinkedHashMap

There are two ways to remove entries in LinkedHashMap.

  1. remove(Object key): It removes key from LinkedHashMap
  2. remove(Object key,Object value): It removes key if value is same as passed parameter value.

Output:

{Bus=120, Car=2200, Rail=680, Flight=4000}
===============================
Vehicle Car with fare 2200 removed from HashMap
{Bus=120, Rail=680, Flight=4000}
================================
Did car removed from LinkedHashMap: false
{Bus=120, Rail=680, Flight=4000}
===============================
Did Flight removed from LinkedHashMap: true
{Bus=120, Rail=680}
===============================

Important LinkedHashMap methods

get(): Retrieve value from the LinkedHashMap
put(): Put value into the LinkedHashMap
isEmpty: Check if LinkedHashMap is empty.
containsKey(): Check if key present is LinkedHashMap
containsValue(): Check if value exists in LinkedHashMap
size(): Check size of the LinkedHashMap
clear(): To remove all elements from LinkedHashMap
clone(): It creates shallow copy of LinkedHashMap.

Here is an example to cover these methods.

Output:

is profDeptmap empty: true
{Arvind=Chemistry, Venkat=Physics, Mary=History, David=Maths}
size of profDeptmap: 4
Venkat’s department: Physics
Hamlet’s department: null
profDeptmap has David as key
profDeptmap has History as value
{}

Get entrySet(), keySet() and values() from LinkedHashMap

entrySet()

entrySet(): As HashMap stores key value pair in form of Entry, we can retrieve entrySet() by calling map.entrySet()

keySet()

keySet(): Provides a set of keys.

values()

values(): Provides a collection of values.

Here is the example for the same.

Output:

EntrySet: [1001=Andrew, 1002=Martin, 1003=Sameer, 1004=Venkat] keySet: [1001, 1002, 1003, 1004] values: [Andrew, Martin, Sameer, Venkat]

As you can see, all the pairs or values are in insertion order.

Iterate over LinkedHashMap

There are many ways to iterate over LinkedHashMap

  1. Iterating over LinkedHashMap using keyset()
  2. Iterating over LinkedHashMap using keyset() with foreach() and lambda expression( java 8)
  3. Iterating over LinkedHashMap using foreach()and lambda expression (java 8)
  4. Iterating over LinkedHashMap’s entrySet() using iterator
  5. Iterating over LinkedHashMap’s entrySet() using foreach() and lambda expression [java 8]
  6. Iterating over LinkedHashMap’s entrySet() using foreach loop

Output:

=========================================================
Iterating over LinkedHashMap with foreach and lambda:
India –> 13000
China –> 15000
Germany –> 9000
France –> 7000
=========================================================
Iterating over LinkedHashMap using keyset() with foreach loop:
India –> 13000
China –> 15000
Germany –> 9000
France –> 7000
=========================================================
Iterating over LinkedHashMap keyset() with foreach and lambda:
India –> 13000
China –> 15000
Germany –> 9000
France –> 7000
=========================================================
Iterating over LinkedHashMap entrySet with iterator
India –> 13000
China –> 15000
Germany –> 9000
France –> 7000
=========================================================
Iterating over LinkedHashMap’s entrySet with foreach and lambda
India –> 13000
China –> 15000
Germany –> 9000
France –> 7000
=========================================================
Iterating over LinkedHashMap’s entrySet with foreach loop
India –> 13000
China –> 15000
Germany –> 9000
France –> 7000

Access order LinkedHashMap

In case, if you want to retrieve entries from LinkedHashMap in access order, you can use LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) constructor.
Let me provide you realtime usecase of LinkedHashMap with access order.

You can use LinkedHashMap with access order to implement LRU cache.
Create a class named LRULHCache

Output

LinkedHashMap: {2=12000, 40=70000}
12000
LinkedHashMap: {40=70000, 2=12000}
LinkedHashMap: {2=12000, 20=70000}
12000
LinkedHashMap: {20=70000, 2=12000}
null

As you can see we have created LRULHCache with capacity 2 and once we call get(), LinkedHashMap is renewed with that key.

Is LinkedHashMap thread-safe?

LinkedHashMap is not thread-safe by default and it can give non-deterministic results in case of a multithreaded environment.

If multiple threads try to access LinkedHashMap and one of them does the structural modification, then it should be externally synchronized.

Best way to do this at LinkedHashMap creation time.

I have already provided an example for HashMap thread safety, since same example is applicable for LinkedHashMap, you can go through this.

Conclusion

You have learned about basics of LinkedHashMap, how to create a LinkedHashMap and add key-value pairs to it, important LinkedHashMap methods, how to iterate over LinkedHashMap and thread safety issues with LinkedHashMap and how to synchronized a LinkedHashMap.
That’s all about HashMap in java.


import_contacts

You may also like:

Related Posts

  • 02 October

    Initialize ArrayList with values in Java

    In this article, we will learn to initialize ArrayList with values in Java. ArrayList is an implementation class of List interface in Java. It is used to store elements. It is based on a dynamic array concept that grows accordingly. We can Initialize ArrayList with values in several ways. Let’s see some of them with […]

  • 17 March

    PriorityQueue in Java 8

    In this post, we will see about Java 8 PriorityQueue. When the objects are supposed to be processed on the basis of their priority, in that scenario we use PriorityQueue. It’s a special type of queue (also, unbound queues) where the elements can be ordered either as per their natural ordering or based on a […]

  • 06 October

    2d Arraylist java example

    In this post, we will see how to create 2d Arraylist in java. Best way to create 2d Arraylist is to create list of list in java. [crayon-60378ab6c8f3f821450742/] Let’s create a program to implement 2d Arraylist java. [crayon-60378ab6c8f46888983701/] Output: 2nd element in list3 : List3_Str2 3nd element in list1 : List1_Str3 1st element in list2 […]

  • 04 May

    How HashMap works in java

    Most common interview questions are <code>How HashMap works in java</code>, “How get and put method of HashMap work internally”. Here I am trying to explain internal functionality with an easy example. [crayon-60378ab70273b645209464-i/]  is one of the most used Collections in java.Rather than going through theory, we will start with example first, so that you will […]

  • 21 October

    How to Sort HashSet in Java

    In this post, we will see how to sort HashSet in java. HashSet is a collection which does not store elements in any order. You might come across a situation where you need to sort HashSet. There can be many ways to sort HashSet, we will see two methods here. Using TreeSet You can use […]

  • 20 October

    Java Array to Set

    In this post, we will learn java array to set conversion. There are many ways to convert array to set. 1. Using Java 8’s Stream If you are using Java 8, I would recommend using this method. [crayon-60378ab6c9755030450648/] Output [John, Martin, Mary] 2. Using HashSet constructor() We can directly call HashSet‘s constructor for java set […]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.