Home » Java » Core Java » LinkedHashMap In Java

About Shubhra Srivastava

Shubhra Srivastava
Shubhra is a software professional and founder of ProgrammerGirl. She has a great experience with Java/J2EE technologies and frameworks. She loves the amalgam of programming and coffee :)

LinkedHashMap In Java

Introduction:

LinkedHashMap is a Map implementation which maintains the insertion order of its elements. It extends the HashMap class:

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

Just like a HashMap, it allows storing one null key and many null values.

Instantiating LinkedHashMap:

We can use one of the following constructors to create a LinkedHashMap:

LinkedHashMap() //default capacity 16 with load factor of 0.75
 
LinkedHashMap(Map<? extends K,? extends V> map)
 
LinkedHashMap(int initialCapacity)
 
LinkedHashMap(int initialCapacity, float loadFactor)
 
LinkedHashMap(int initialCapacity, float loadFactor
  , boolean accessOrder)

The very last constructor also accepts a boolean argument accessOrder.

When we pass true to the accessOrder, we’re instantiating an access-order LinkedHashMap. An access-order LinkedHashMap maintains the access order of elements from the least-recently-used to the most-recently-used, instead of the insertion order.

Types Of LinkedHashMap:

We can classify a Java LinkedHashMap in two main categories:

1. Insertion-Order LinkedHashMap:

Unless stated otherwise, a LinkedHashMap maintains the insertion order of its elements. We can name it as an insertion-order LinkedHashMap.

Let’s look at an example:

@Test
public void insertionOrderLinkedHashMap() {
 
    LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
    map.put(1, "A");
    map.put(2, "B");
    map.put(3, "C");
   
    assertEquals("[1, 2, 3]", map.keySet().toString());
  
    map.get(2); // accessing element
 
    assertEquals("[1, 2, 3]", map.keySet().toString()); //still maintains insertion order
    
}

2. Access-Order LinkedHashMap:

When we use the constructor: LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) and pass a true value to the accessOrder argument, we’ll have an access-order LinkedHashMap.

Let’s see how an access-order LinkedHashMap actually works:

@Test
public void accessOrderLinkedHashMap() {
 
    LinkedHashMap<Integer, String> map = new LinkedHashMap<>(16, 0.75f, true);
    map.put(1, "A");
    map.put(2, "B");
    map.put(3, "C");
   
    assertEquals("[1, 2, 3]", map.keySet().toString());
  
    map.get(2); // accessing element
 
    assertEquals("[1, 3, 2]", map.keySet().toString());
    
}

On accessing the element with the key as 2, it moved to the very last position. Clearly, the elements are ordered based on their access order from the least recent to the most recent.

Commonly Used Methods:

Let’s explore the popular methods:

  1. V put(K key, V value): inherits this method from the HashMap class. It stores the given key-value pair. If the key already exists, the value is updated
  2. void replaceAll(BiFunction<? super K, ? super V, ? extends V> function): replaces each entry’s value with the result of invoked function on that entry until all entries have been processed or the function throws an exception
  3. boolean containsKey(Object key): to check if a given key exists
  4. boolean containsValue(Object value): returns true if there’s at least one key with that value
  5. V get(Object key): to retrieve a value based on key
  6. V getOrDefault(Object key, V defaultValue): returns the mapped value if the key exists or else returns the default value
  7. void clear(): to remove all the elements
  8. Set<Map.Entry<K, V>> entrySet(): returns a Set view of the mappings in the given map
  9. Set<K> keySet(): returns a Set view of keys contained in the map
  10. Collection<V> values(): returns a Collection view of values contained in the map
  11. forEach(BiConsumer<? super K, ? super V> action): performs a given action on each entry in the given map until either all entries are processed or an exception gets thrown
  12. protected boolean removeEldestEntry(Map.Entry<K< V> eldest): this method will return true if the map should remove its eldest entry

Let’s now try out a few of these methods:

Map<Integer, String> map = new LinkedHashMap<>();
 
map.put(1, "A");
map.put(2, "B");
 
map.forEach((k, v) -> System.out.println(k + ":" + v));
 
System.out.println(map.size());
 
System.out.println(map.containsKey(1));
 
System.out.println(map.get(1));
 
map.remove(1);
 
for(Map.Entry<Integer, String> entry : map.entrySet()) {
    System.out.println("Key=" + entry.getKey() + ", Value=" + entry.getValue());
}

 Conclusion:

In this quick article, we looked at what a LinkedHashMap is and how can we instantiate and use it.

Be the First to comment.

Published on Java Code Geeks with permission by Shubhra Srivastava, partner at our JCG program. See the original article here: LinkedHashMap In Java

Opinions expressed by Java Code Geeks contributors are their own.

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of