LinkedHashSet in java with example

In this post, we will see about LinkedHashSet in java. LinkedHashSet is same as HashSet except that it maintains insertion order.

Some points about LinkedHashSet
  1. LinkedHashSet implements Set interface and extends HashSet class.
  2. LinkedHashSet maintains insertion order, so when you will be able to access elements in the order they were inserted like ArrayList.

Example:

LinkedHashSetMain.java
package org.arpit.java2blog;

import java.util.LinkedHashSet;

public class LinkedHashSetMain {

 public static void main(String args[])
 {
 // LinkedHashSet with Country
 // LinkedHashSet maintains insertion order  
  LinkedHashSet<String> countryHashSet=new LinkedHashSet<String>();
  countryHashSet.add("India");
  countryHashSet.add("Japan");
  countryHashSet.add("France");
  countryHashSet.add("Russia");
  countryHashSet.add("India");
  countryHashSet.add("France");
  countryHashSet.add("United Kingdom");

  System.out.println("-----------------------------");
 
  System.out.println("Iterating LinkedHashSet");
  System.out.println("-----------------------------");
  for (String country:countryHashSet) {
   System.out.println(country);

  }
  System.out.println("-----------------------------");
}

}

When you run above program, you will get below output:
-----------------------------
Iterating LinkedHashSet
-----------------------------
India
Japan
France
Russia
United Kingdom
-----------------------------

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012