LinkedHashMap Class

In this chapter you will learn:

  1. How to use LinkedHashMap

Use LinkedHashMap

LinkedHashMap extends HashMap. It maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map.

LinkedHashMap is a generic class that has this declaration:

class LinkedHashMap<K, V>
  • K specifies the type of keys
  • V specifies the type of values.

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> e)

This method is called by put( ) and putAll( ). The oldest entry is passed in e.

import java.util.LinkedHashMap;
/*ja v  a2 s  .com*/
public class Main {

  public static void main(String[] args) {
    LinkedHashMap<Integer, Integer> linkedMap = new LinkedHashMap<Integer, Integer>();
    for (int i = 0; i < 10; i++) {
      linkedMap.put(i, i);
    }

    System.out.println(linkedMap);
    // Least-recently used order:
    linkedMap = new LinkedHashMap<Integer, Integer>(16, 0.75f, true);

    for (int i = 0; i < 10; i++) {
      linkedMap.put(i, i);
    }
    System.out.println(linkedMap);
    for (int i = 0; i < 7; i++)
      System.out.println(linkedMap.get(i));
    System.out.println(linkedMap);
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to use IdentityHashMap
  2. What are the difference between IdentityHashMap and HashMap
Home » Java Tutorial » Map
Map interface
Map element adding
Map.Entry class
Map key
Map value
Map key/value search
Map delete/remove
Map comparison
HashMap Class
HashMap search
HashMap clone
TreeMap
TreeMap key
TreeMap head sub map
TreeMap tail sub map
TreeMap sub map
NavigableMap
NavigableMap key
NavigableMap key-value pair
LinkedHashMap Class
IdentityHashMap
SortedMap