Pages

Saturday, April 4, 2020

LinkedHashMap in Java With Example Programs + Java 8 New Methods

1. Introduction


In this tutorial, We'll learn LinkedHashMap API in java with example programs.

LinkedHashMap is used to store the key-value pairs as similar to the HashMap. But, LinkedHashMap extends HashMap and AbstractMap implements Map interface. The main advantage of LinkedHashMap is it preserves the insertion order that meanwhile iterating it pull the Entry Objects how the order keys are inserted into LinkedHashMap.

Iterating over collection in java

We have discussed HashMap in-depth with all methods examples including java 8 concepts. It is good to go over the HashMap article that makes you answer interview questions on all of its methods.


If you do not understand at any point just leave your question in comments.

LinkedHashMap in Java With Example Programs + Java 8 New Methods




2. LinkedHashMap Key Features


Below are the key factors of LinkedHashMap.


    1. LinkedHashMap stores the key value pairs.
    2. LinkedHashMap uses the internally Double LinkedList.
    3. LinkedHashMap preserves the insertion order and this order is done using Linked List which holds the address of the next Entry object.
    4. LinkedHashMap does not allow duplicate keys
    5. LinkedHashMap allows only one null key and allows multiple null values.
    6. LinkedHashMap is not synchronized
    7. LinkedHashMap has all features of HashMap except holding the insertion order.

3. Internals

3.1 Hierarchy

Below are the classes and interfaces that are involved in implementation.

java.lang.Object
java.util.AbstractMap<K,V>
java.util.HashMap<K,V>
java.util.LinkedHashMap<K,V> 

3.2 Class declaration:


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

3.3 Entry class


Below is the Entry class implementation and it is extending HashMap.Node class. It has two references for Entry type those are to hold before and after entry refs. If a key/value is added to the map and immediately it will be added with before and after entry object references.

static class Entry<K,V> extends HashMap.Node<K,V> {
    Entry<K,V> before, after;
    Entry(int hash, K key, V value, Node<K,V> next) {
        super(hash, key, value, next);
    }
}

4. Creating LinkedHashMap Objects


LinkedHashMap has 5 constructors to create its object.

Way 1: Creates an empty map with size 16.
Way 2: With an initial capacity
Way 3: Creating from an existing map
Way 4: With the size and load factor
Way 5: With size, load factor and access order. true for accessing order and false for insertion order.

// creating LinkedHashMap way
LinkedHashMap<Integer, String> way1 = new LinkedHashMap<>();

// way 2
LinkedHashMap<Integer, String> way2 = new LinkedHashMap<>(25);

// way 3
LinkedHashMap<Integer, String> way3 = new LinkedHashMap<>(way2);

// way 4
LinkedHashMap<Integer, String> way4 = new LinkedHashMap<>(50, 0.5f);

// way 5
LinkedHashMap<Integer, String> way5 = new LinkedHashMap<>(75, 0.75f, false);

5. LinkedHashMap Methods


This gets all methods of the HashMap but the below are directly from LinkedHashMap.


  • clear(): Removes all of the mappings from this map.
  • containsValue(Object value): Returns boolean value true if the specified value is present in the map else returns false.
  • entrySet(): Returns a Set of Entry&lt;K, V&gt; objects. Returned Set is tightly linked to the underlying map. If the Map is modified then the returned Set will be reflected with modifications.
  • forEach(BiConsumer biconsumer): Executes the BiConsumer logic to each key-value pair in the map.
  • get(Object key): Returns the value for the specified key. Returns null if the key is not present in the map.
  • getOrDefault(Object key, V defaultValue): Returns the value for the specified key. If key does not exits then return the default value that we have passed.
  • keySet(): Returns all keys in the form of Set.
  • removeEldestEntry(Map.Entry<K,V> eldest): Returns true if this map should remove its eldest entry
  • replaceAll(BiFunction function): BiFunction logic is executed for all keys and returned value will be updated as a new value in the map for each key.
  • values(): Returns all values as Collection


You may get a question

why only the above methods are implemented as part of LinkedHashMap instead of using from HashMap class?

Answer: As mentioned earlier, This class holds pointers as below. If any methods that are needed to interact with these set of pointers those methods are added as part of LinkedHashMap.

transient LinkedHashMap.Entry<K,V> head;
transient LinkedHashMap.Entry<K,V> tail;

Entry<K,V> before, after;

final boolean accessOrder;

6. LinkedHashMap All Methods Example

Below is the example program for all methods.

package com.java.w3schools.blog.linkedhashmap;

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

public class LinkedHashMapExample {

 public static void main(String[] args) {

  // creating LinkedHashMap way
  LinkedHashMap<Integer, String> way1 = new LinkedHashMap<>();

  // way 2
  LinkedHashMap<Integer, String> way2 = new LinkedHashMap<>(25);

  // way 3
  LinkedHashMap<Integer, String> way3 = new LinkedHashMap<>(way2);

  // way 4
  LinkedHashMap<Integer, String> way4 = new LinkedHashMap<>(50, 0.5f);

  // way 5
  LinkedHashMap<Integer, String> way5 = new LinkedHashMap<>(75, 0.75f, false);

  // Adding values to LinkedHashMap
  System.out.println("\nput example");
  way5.put(111, "One");
  way5.put(222, "Two");
  way5.put(333, "Three");
  way5.put(444, "Four");
  way5.put(555, "Five");

  String value111 = way5.get(111);
  System.out.println("value of key 111 : " + value111);

  // getOrDefault example
  System.out.println("\ngetOrDefault example");
  String valueDefault = way5.getOrDefault(5000, "No Key Found");
  System.out.println("get default value : " + valueDefault);

  String value333 = way5.compute(333, (k, v) -> (v + " - " + k));
  System.out.println("compute example : " + value333);

  // containsKey example
  System.out.println("\ncontainsKey example");
  boolean key555Present = way5.containsKey(555);
  System.out.println("555 key present : " + key555Present);

  // forEach example
  System.out.println("\nforEach example");
  way5.forEach((key, value) -> System.out.println("key - " + key + ", Value - " + value));

  // containsValue example
  System.out.println("\ncontainsValue example");
  System.out.println(way5.containsValue("Five"));

  // entrySet example
  System.out.println("\nentrySet example");
  Set<Entry<Integer, String>> s = way5.entrySet();

  Iterator<Entry<Integer, String>> it = s.iterator();

  while (it.hasNext()) {
   Entry<Integer, String> e = it.next();
   System.out.println(e.getKey() + " ---- " + e.getValue());
  }

  // keySet example
  System.out.println("\nkeySet example");
  Set<Integer> keySet = way5.keySet();

  Iterator<Integer> keyIterator = keySet.iterator();
  while (keyIterator.hasNext()) {
   System.out.println(keyIterator.next());
  }

  // replaceAll example
  System.out.println("\n replaceAll example");
  way5.replaceAll((k, v) -> (k + v));
  System.out.println(way5);
  
  
  
  // clear() example
  way5.clear();
  System.out.println(way5.size());

  
 }

}

Output:

put example
value of key 111 : One

getOrDefault example
get default value : No Key Found
compute example : Three - 333

containsKey example
555 key present : true

forEach example
key - 111, Value - One
key - 222, Value - Two
key - 333, Value - Three - 333
key - 444, Value - Four
key - 555, Value - Five

containsValue example
true

entrySet example
111 ---- One
222 ---- Two
333 ---- Three - 333
444 ---- Four
555 ---- Five

keySet example
111
222
333
444
555

 replaceAll example
{111=111One, 222=222Two, 333=333Three - 333, 444=444Four, 555=555Five}
0

7. Conclusion


In this article, We've seen What is LinkedHashMap API and What is the importance. When we should use this? Shown example programs for all its methods.

If you want to store a key-value pairs and insertion order needs to be preserved then we should go with this. This is similar to the HashMap except it holds the order of insertion.

GitHub

Ref API

No comments:

Post a Comment

Please do not add any spam links in the comments section.