Java LinkedHashMap : Collection Class

Java LinkedHashMap : Collection Class

  1. LinkedHashMap contains only unique elements or key.
  2. LinkedHashMap class extends HashMap.
  3. LinkedHashMap maintains a linked list of the entries in the map in the order in which they were inserted.
  4. LinkedHashMap allows insertion-order iteration over the map i.e elements will be returned in the order of insertion.
  5. LinkedHashMap can also returns its elements in the order in which they were last accessed.
  6. LinkedHashMap can have same value but key’s must be unique.

Lets create an LinkedHashMap using following line of code –

Example #1 : Create LinkedHashMap

package com.c4learn.collection;

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

public class LinkedHashMapExample {
  public static void main(String[] args) {

  LinkedHashMap<String, String> hMap = new 
			LinkedHashMap<String, String>();

  hMap.put("A1", "Aman");
  hMap.put("A2", "Arun");
  hMap.put("A3", "Akash");
  hMap.put("A4", "Aniket");
  hMap.put("A5", "Anil");

  Set set = hMap.entrySet();
  Iterator itr = set.iterator();

  while (itr.hasNext()) {
    Map.Entry m = (Map.Entry);
    System.out.println(m.getKey() + " " + m.getValue());

Output :

A1 Aman
A2 Arun
A3 Akash
A4 Aniket
A5 Anil