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.

Was this post helpful?

Leave a Reply

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