LinkedHashMap java code example

Example 1: linkedhashmap in java

LinkedHashMap is same as HasHMap just additionally maintains the insertion order.

Example 2: hashmap and linkedhashmap

Main difference between HashMap and LinkedHashMap
I remember is that LinkedHashMap maintains
insertion order of keys, 
On the other hand HashMap doesn't maintain
any order or keys or values.
Also LinkedHashMap requires more memory than HashMap
because of the ordering feature.
LinkedHashMap doublly Linked List to 
maintain order of elements.

Example 3: linkedhashmap in java

LinkedHashMap can have null key, keeps order

Example 4: LinkedHashSet in java

import java.util.LinkedHashSet;
public class LinkedHashsetExample
{
   public static void main(String[] args)
   {
      LinkedHashSet<String> lhs = new LinkedHashSet<String>();
      // add elements to LinkedHashSet
      lhs.add("Anteater");
      lhs.add("Bear");
      lhs.add("Cheetah");
      lhs.add("Deer");
      // will not add new element as Anteater already exists
      lhs.add("Anteater");
      lhs.add("Elephant");
      System.out.println("LinkedHashSet size: " + lhs.size());
      System.out.println("Given LinkedHashSet: " + lhs);
      System.out.println("Deer removed from LinkedHashSet: " + lhs.remove("Deer"));
      System.out.println("Remove Zebra which is not present: " + lhs.remove("Zebra"));
      System.out.println("Check if Anteater is present: " + lhs.contains("Anteater"));
      System.out.println("New LinkedHashSet: " + lhs);
   }
}

Tags:

Java Example