Java LinkedHashMap - LinkedHashMap in Java - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Tuesday, March 7, 2017

Java LinkedHashMap - LinkedHashMap in Java

What is LinkedHashMap in Java?

LinkedHashMap is HashTable and linked list implementation of the Map interface with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map(insertion-order). In last few posts we have discussed about HashMap and TreeMap.

Here is the topic that will cover in this post.

  1. LinkedHashMap class Declaration
  2. LinkedHashMap features
  3. LinkedHashMap constructors
  4. LinkedHashMap class Methods
  5. Example
  6. Iterate or Traverse over LinkedHashMap

Java LinkedHashMap class Declaration

The LinkedHashMap class extends HashMap and implements the Map interface. LinkedHashMap is a generic class that has this declaration:

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

Here, K specifies the type of keys, and V specifies the type of values.

Java LinkedHashMap features

  1. Java LinkedHashMap inherits HashMap class.
  2. Java LinkedHashMap implements the Map interface.
  3. Java LinkedHashMap permits one null key and multiple null values.
  4. Java LinkedHashMap can not be used for primitive types, like int, char, etc. We need to use wrapper classes.
  5. Java LinkedHashMap is not synchronized.
  6. Java LinkedHashMap is not thread-safe. You can make thread-safe by doing
    Map m = Collections.synchronizedMap(new LinkedHashMap(...));
  7. Java LinkedHashMap maintains the insertion order. It is internally maintains a doubly-linked list running through all of its entries.
  8. Java LinkedHashMap implementation provides constant-time performance for the basic operations (get, contains, remove and put), assuming the hash function disperses the elements properly among the buckets.
  9. Java LinkedHashMap performance is likely to be just slightly below to HashMap, due to the added expense of maintaining the linked list, with one exception: Iteration over the collection-views of a LinkedHashMap requires time proportional to the size of the map, regardless of its capacity. Iteration over a HashMap is likely to be more expensive, requiring time proportional to its capacity.
  10. A LinkedHashMap has two parameters that affect its performance: initial capacity and load factor.
  11. The iterators returned by all of this class's "collection view methods" are fail-fast.

Java LinkedHashMap constructors

Java LinkedHashMap have five constructors.

Constructor Description
public LinkedHashMap() Constructs an empty insertion-ordered LinkedHashMap instance with the default initial capacity (16) and load factor (0.75).
public LinkedHashMap(int initialCapacity) Constructs an empty insertion-ordered LinkedHashMap instance with the specified initial capacity and a default load factor (0.75).
public LinkedHashMap(int initialCapacity, float loadFactor) Constructs an empty insertion-ordered LinkedHashMap instance with the specified initial capacity and load factor.
public LinkedHashMap(Map<? extends K, ? extends V> m) Constructs an insertion-ordered LinkedHashMap instance with the same mappings as the specified map. The LinkedHashMap instance is created with a default load factor (0.75) and an initial capacity sufficient to hold the mappings in the specified map.
public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) Constructs an empty LinkedHashMap instance with the specified initial capacity, load factor and ordering mode (ordering mode - true for access-order, false for insertion-order)

Below code snippet show example to create LinkedHashMap instances using it's constructors.


    LinkedHashMap<Integer, String> linkedHashMap1 = new LinkedHashMap<>();

    LinkedHashMap<Integer, String> linkedHashMap2 = new LinkedHashMap<>(10);

    LinkedHashMap<Integer, String> linkedHashMap3 = new LinkedHashMap<>(32, 0.85f);

    // access order will use
    LinkedHashMap<Integer, String> linkedHashMap4 = new LinkedHashMap<>(32, 0.85f, true);

    LinkedHashMap<Integer, String> linkedHashMap5 = new LinkedHashMap<>(linkedHashMap1);

    

Java LinkedHashMap methods

LinkedHashMap adds only one method to those defined by HashMap. This method is removeEldestEntry( ), and it is shown here:

protected boolean removeEldestEntry(Map.Entry<K, V> eldest)

This method is called by put( ) and putAll( ). The oldest entry is passed in eldest. By default, this method returns false and does nothing. However, if you override this method, then you can have the LinkedHashMap remove the oldest entry in the map. To do this, have your override return true. To keep the oldest entry, return false.

Example

Here is a simple program of LinkedHashMap using common methods.

package com.walking.techie;

import java.util.LinkedHashMap;

public class LinkedHashMapDemo {

  public static void main(String[] args) {
    LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<>();
    linkedHashMap.put(100, "Continue");
    linkedHashMap.put(101, "Switching Protocols");
    linkedHashMap.put(102, "Processing");
    linkedHashMap.put(400, "Bad Request");
    linkedHashMap.put(401, "Unauthorized");
    linkedHashMap.put(405, "Method Not Allowed");
    linkedHashMap.put(200, "OK");
    linkedHashMap.put(202, "Accepted");
    linkedHashMap.put(203, "Non Authoritative Information");
    linkedHashMap.put(500, "Server Error");
    linkedHashMap.put(503, "Service Unavailable");
    linkedHashMap.put(507, "Insufficient Storage");
    linkedHashMap.put(511, "Network Authentication Required");
    linkedHashMap.put(300, "Multiple Choices");
    linkedHashMap.put(302, "Moved Temporarily");
    for (Integer key : linkedHashMap.keySet()) {
      System.out.println("Key : " + key + " Value : " + linkedHashMap.get(key));
    }
  }
}

Output of above program is shown below:

Key : 100 Value : Continue
Key : 101 Value : Switching Protocols
Key : 102 Value : Processing
Key : 400 Value : Bad Request
Key : 401 Value : Unauthorized
Key : 405 Value : Method Not Allowed
Key : 200 Value : OK
Key : 202 Value : Accepted
Key : 203 Value : Non Authoritative Information
Key : 500 Value : Server Error
Key : 503 Value : Service Unavailable
Key : 507 Value : Insufficient Storage
Key : 511 Value : Network Authentication Required
Key : 300 Value : Multiple Choices
Key : 302 Value : Moved Temporarily

Access order of LinkedHashMap in java

package com.walking.techie;

import java.util.LinkedHashMap;

public class LinkedHashMapTraversal {

  public static void main(String[] args) {
    LinkedHashMap<Integer, String> lHashMap = new LinkedHashMap<>(8, 0.75f, true);
    lHashMap.put(100, "Continue");
    lHashMap.put(400, "Bad Request");
    lHashMap.put(200, "OK");
    lHashMap.put(500, "Server Error");
    lHashMap.put(300, "Multiple Choices");

    int key1 = 200;
    System.out.println("1. Accessing value at key : " + key1 + " is " + lHashMap.get(key1));
    int key2 = 500;
    System.out.println("2. Accessing value at key : " + key2 + " is " + lHashMap.get(key2));
    // using java 8 for each and lambda expression
    lHashMap.forEach((k, v) -> {
      System.out.println("Key=" + k + " Value=" + v);
    });
  }
}

Output of above program is shown below:

1. Accessing value at key : 200 is OK
2. Accessing value at key : 500 is Server Error
Key=100 Value=Continue
Key=400 Value=Bad Request
Key=300 Value=Multiple Choices
Key=200 Value=OK
Key=500 Value=Server Error

Iterate or Traverse over LinkedHashMap

1. Iterating LinkedHashMap in java using iterator and KeySet

package com.walking.techie;

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

public class LinkedHashMapTraversal {

  public static void main(String[] args) {
    LinkedHashMap<Integer, String> lHashMap = new LinkedHashMap<>();
    lHashMap.put(100, "Continue");
    lHashMap.put(400, "Bad Request");
    lHashMap.put(200, "OK");
    lHashMap.put(500, "Server Error");
    lHashMap.put(300, "Multiple Choices");

    // Returns a Set view of the keys contained in this map.
    Set<Integer> set = lHashMap.keySet();

    // Returns an iterator over the elements in this set.
    Iterator<Integer> itr = set.iterator();
    while (itr.hasNext()) {
      Integer key = itr.next();
      System.out.println("Key=" + key + " Value=" + lHashMap.get(key));
    }
  }
}

Output of above program is shown below:

Key=100 Value=Continue
Key=400 Value=Bad Request
Key=200 Value=OK
Key=500 Value=Server Error
Key=300 Value=Multiple Choices

2. Iterating LinkedHashMap in java using EntrySet and Java Iterator

package com.walking.techie;

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

public class LinkedHashMapTraversal {

  public static void main(String[] args) {
    LinkedHashMap<Integer, String> lHashMap = new LinkedHashMap<>();
    lHashMap.put(100, "Continue");
    lHashMap.put(400, "Bad Request");
    lHashMap.put(200, "OK");
    lHashMap.put(500, "Server Error");
    lHashMap.put(300, "Multiple Choices");

    // Returns a Set view of the mappings contained in this map.
    Set<java.util.Map.Entry<Integer, String>> entry = lHashMap.entrySet();

    // Returns an iterator over the elements in this set.
    Iterator<Entry<Integer, String>> iterator = entry.iterator();
    while (iterator.hasNext()) {
      Map.Entry<Integer, String> entry2 = (Entry<Integer, String>) iterator.next();
      System.out.println("Key=" + entry2.getKey() + " Value=" + entry2.getValue());
    }
  }
}

Output of above program is shown below:

Key=100 Value=Continue
Key=400 Value=Bad Request
Key=200 Value=OK
Key=500 Value=Server Error
Key=300 Value=Multiple Choices

3. Iterating LinkedHashMap in java using EntrySet and Java for loop

package com.walking.techie;

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

public class LinkedHashMapTraversal {

  public static void main(String[] args) {
    LinkedHashMap<Integer, String> lHashMap = new LinkedHashMap<>();
    lHashMap.put(100, "Continue");
    lHashMap.put(400, "Bad Request");
    lHashMap.put(200, "OK");
    lHashMap.put(500, "Server Error");
    lHashMap.put(300, "Multiple Choices");

    Set<Entry<Integer, String>> entrySet = lHashMap.entrySet();
    for (Entry<Integer, String> entry : entrySet) {
      System.out.println("Key=" + entry.getKey() + " Value=" + entry.getValue());
    }
  }
}

Output of above program is shown below:

Key=100 Value=Continue
Key=400 Value=Bad Request
Key=200 Value=OK
Key=500 Value=Server Error
Key=300 Value=Multiple Choices

4. Iterating LinkedHashMap in java using KeySet and Java for loop

package com.walking.techie;

import java.util.LinkedHashMap;

public class LinkedHashMapTraversal {

  public static void main(String[] args) {
    LinkedHashMap<Integer, String> lHashMap = new LinkedHashMap<>();
    lHashMap.put(100, "Continue");
    lHashMap.put(400, "Bad Request");
    lHashMap.put(200, "OK");
    lHashMap.put(500, "Server Error");
    lHashMap.put(300, "Multiple Choices");

    for (Integer key : lHashMap.keySet()) {
      System.out.println("Key=" + key + " Value=" + lHashMap.get(key));
    }
  }
}

Output of above program is shown below:

Key=100 Value=Continue
Key=400 Value=Bad Request
Key=200 Value=OK
Key=500 Value=Server Error
Key=300 Value=Multiple Choices

5. Iterating LinkedHashMap in java using Java 8 forEach and lambda expression

package com.walking.techie;

import java.util.LinkedHashMap;

public class LinkedHashMapTraversal {

  public static void main(String[] args) {
    LinkedHashMap<Integer, String> lHashMap = new LinkedHashMap<>();
    lHashMap.put(100, "Continue");
    lHashMap.put(400, "Bad Request");
    lHashMap.put(200, "OK");
    lHashMap.put(500, "Server Error");
    lHashMap.put(300, "Multiple Choices");

    // using java 8 for each and lambda expression
    lHashMap.forEach((k, v) -> {
      System.out.println("Key=" + k + " Value=" + v);
    });
  }
}

Output of above program is shown below:

Key=100 Value=Continue
Key=400 Value=Bad Request
Key=200 Value=OK
Key=500 Value=Server Error
Key=300 Value=Multiple Choices

No comments :

Post a Comment