LinkedHashSet in java

LinkedHashSet extends HashSet and implements the Set interface. It maintains insertion order for its elements. There are certain important points about the  LinkedHashSet class which is required to understand while using the LinkedHashSet class.

  • Similar to the HashSet class, the LinkedHashSet class can also hold the unique elements only.
  • It facilitates all optional set operations.
  • It is non-synchronized.
  • It allows null elements.
  • The insertion order is maintained by the LinkedHashSet class.

Hierarchy of LinkedHashSet class:

The HashSet class is extended by the LinkedHashSet class which implements the Set interface. The Collection and Iterable interfaces are inherited by the Set interface in hierarchical order.

LinkedHashSet class declaration:

public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, Serializable

Constructors of Java LinkedHashSet class:

Sl.No. Constructor Description
1 HashSet() To construct a default HashSet.
2 HashSet(Collection c) To initialize the hash set by using the elements of the collection c.
3 LinkedHashSet(int capacity) To initialize the capacity of the linked hash set to the given integer value capacity.
4 LinkedHashSet(int capacity, float fillRatio) To initialize both the capacity and the fill ratio (also called load capacity) of the hash set from its argument.

LinkedHashSet example:

LinkedHashSetTest.java

import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
 
/**
 * This class is used to show the LinkedHashSet functionality.
 * @author w3schools
 */
public class LinkedHashSetTest {
	public static void main(String args[]){
		//Create LinkedHashSet object.
		Set linkedHashSet = new LinkedHashSet();
 
		//Add objects to the LinkedHashSet.
		linkedHashSet.add("Pooja");
		linkedHashSet.add("Rupali");
		linkedHashSet.add("Prince");
		linkedHashSet.add("Rachna");
		linkedHashSet.add("Rinku");
 
		//Print the LinkedHashSet object.
		System.out.println("LinkedHashSet elements:");
		System.out.println(linkedHashSet);
 
		//Print the LinkedHashSet elements using iterator.
		Iterator iterator=linkedHashSet.iterator();
		System.out.println("LinkedHashSet elements " +
				"using iterator:");
		while(iterator.hasNext()){  
		   System.out.println(iterator.next());  
		}  
	}
}

Output:

LinkedHashSet elements:
[Pooja, Rupali, Prince, Rachna, Rinku]
LinkedHashSet elements using iterator:
Pooja
Rupali
Prince
Rachna
Rinku

Example: Ignoring duplicate Elements:

import java.util.*;  
public class LinkedHashSetExample{  
 public static void main(String args[]){  
  LinkedHashSet<string> al=new LinkedHashSet<string>();  
  al.add("A");  
  al.add("B");  
  al.add("A");  
  al.add("C");  
  Iterator<string> itr=al.iterator();  
  while(itr.hasNext()){  
   System.out.println(itr.next());  
  }  
 }  
}

Output:

Next Topic: TreeSet in java with example.
Previous Topic: HashSet in java with example.