LinkedHashMap, WeakHashMap and SortedMap


LinkedHashMap

LinkedHashMap class is Hash table and Linked list implementation of the Map interface, with predictable iteration order. It inherits HashMap class and implements the Map interface.

The important points about Java LinkedHashMap class are: A LinkedHashMap contains values based on the key. It contains only unique elements. It may have one null key and multiple null values. It is same as HashMap instead maintains insertion order.

Java LinkedHashMap class

Key Points:

  • Is Hash table and Linked list implementation of the Map interface, with predictable iteration order.
  • inherits HashMap class and implements the Map interface.
  • contains values based on the key.
  • only unique elements.
  • may have one null key and multiple null values.
  • same as HashMap instead maintains insertion order.

Methods:

  • void clear().
  • boolean containsKey(Object key).
  • Object get(Object key).
  • protected boolean removeEldestEntry(Map.Entry eldest)

Example:

import java.util.*;
 
public class DifferentMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("Alice", "Physics");
        map.put("Bob", "Chemistry");
        map.put("Charlie", "Biology");
        map.put("David", "Mathematics");
        map.put("Eve", "Computer Science");
 
        Set<Map.Entry<String, String>> entrySet = map.entrySet();
        Iterator<Map.Entry<String, String>> iterator = entrySet.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
 
        System.out.println("Does the map contain key 'Bob'? " + map.containsKey("Bob"));
        System.out.println("The value for the key 'David' is: " + map.get("David"));
    }
}

WeakHashMap

Key Points:

  • Implementation of Map.
  • stores only weak references to its keys.

Weak References :

The objects that are referenced only by weak references are garbage collected eagerly; the GC won’t wait until it needs memory in that case.

Difference between Hashmap and WeakHashMap :

If the Java memory manager no longer has a strong reference to the object specified as a key, then the entry in the map will be removed in WeakHashMap.

Example:

import java.util.*;
 
public class DifferentWeakHashMapTest {
    public static void main(String[] args) {
        Map<String, String> hashMap = new HashMap<>();
        Map<String, String> weakHashMap = new WeakHashMap<>();
 
        String keyHashMap = new String("keyHashMapTest");
        String keyWeakHashMap = new String("keyWeakHashMapTest");
 
        hashMap.put(keyHashMap, "John");
        weakHashMap.put(keyWeakHashMap, "Doe");
 
        System.gc();
        System.out.println("Before: HashMap value: " + hashMap.get("keyHashMapTest") + " and WeakHashMap value: " 
                + weakHashMap.get("keyWeakHashMapTest"));
 
        keyHashMap = null;
        keyWeakHashMap = null;
 
        System.gc();
 
        System.out.println("After: HashMap value: " + hashMap.get("keyHashMapTest") + " and WeakHashMap value: " 
                + weakHashMap.get("keyWeakHashMapTest"));
    }
}

Size differences (HashMap vs WeakHashMap):

Calling size() method on HashMap object will return the same number of key-value pairs. size will decrease only if remove() method is called explicitly on the HashMap object.

Because the garbage collector may discard keys at anytime, a WeakHashMap may behave as though an unknown thread is silently removing entries. So it is possible for the size method to return smaller values over time.So, in WeakHashMap size decrease happens automatically. .


SortedMap

Key Points:

  • SortedMap interface extends Map.
  • entries are maintained in an ascending key order.

Methods of sorted Map :

  • Comparator comparator( ).
  • Object firstKey( ).
  • SortedMap headMap(Object end).
  • Object lastKey( ).
  • SortedMap subMap(Object start, Object end).
  • SortedMap tailMap(Object start).

Example:

import java.util.*;
 
public class TreeMapExample {
    public static void main(String args[]) {
        // Create a tree map
        TreeMap<String, Double> treeMap = new TreeMap<>();
 
        // Put elements to the map
        treeMap.put("Alice", new Double(3434.34));
        treeMap.put("Bob", new Double(123.22));
        treeMap.put("Charlie", new Double(1378.00));
        treeMap.put("David", new Double(99.22));
        treeMap.put("Eve", new Double(-19.08));
 
        // Get a set of the entries
        Set set = treeMap.entrySet();
 
        // Get an iterator
        Iterator i = set.iterator();
 
        // Display elements
        while (i.hasNext()) {
            Map.Entry me = (Map.Entry) i.next();
            System.out.print(me.getKey() + ": ");
            System.out.println(me.getValue());
        }
        System.out.println();
 
        // Deposit 1000 into Alice's account
        double balance = treeMap.get("Alice");
        treeMap.put("Alice", balance + 1000);
        System.out.println("Alice's new balance: " + treeMap.get("Alice"));
    }
}

Basic Programs