Java LinkedHashSet

In this tutorial, we will learn about functionality of java.util.LinkedHashSet, its use cases along with working examples and includes custom class objects.

LinkedHashSet class

In Java, java.util.LinkedHashSet is class from collections framework which extends HashSet. It provides all the functionality as compared to the HashSet plus maintains the insertion order of elements in it unlike HashSet.

Internal implementation of LinkedHashSet

HashSet is backed by hash table only but in case of LinkedHashSet, backed by hash table along with linked list to maintain insertion order. Important to note that if duplicate elements trying to insert will not affect the insertion order. Performance is somewhat low as compared to the HashSet performance due to maintaining insertion order.

LinkedHashSet use cases:

  1. Where duplicate records should be omitted.
  2. Provides functionality without allowing duplicates along with insertion order.
  3. Can be used graph algorithms.

Now, we will move to the examples of this, which includes user defined classes along with inbuilt classes.

LinkedHashSet example without equals() and hashCode() methods:

In this example we will add string elements to the LinkedHashSet, as we know String class contains the implementation of the equals() and hashCode() methods.

CopiedCopy Code
import java.util.Iterator;
import java.util.LinkedHashSet;  
public class LinkedHashSetExample{  
 public static void main(String args[]){  
	   //Creating LinkedHashSet object with default capacity and load factor  
        LinkedHashSet<String> linkedset=new LinkedHashSet<String>();  
               linkedset.add("Ant");    
               linkedset.add("Ball");    
               linkedset.add("Cat");   
               linkedset.add("Dog");  
               linkedset.add("Egg");  
               Iterator<String> iterator=linkedset.iterator();  
               while(iterator.hasNext())  
               {  
               System.out.println(iterator.next());  
               }  
 }  
}

Output:

Ant
Ball
Cat
Dog
Egg

Explanation:

Created a LinkedHashSet object to allow elements of String type, added five elements to understand better kept in alphabetical order.

Later printed all the elements in it by using Iterator and all the elements in the same order which they were inserted.

LinkedHashSet example with equals() and hashCode() methods:

In this example, we will add elements belongs to the user defined or custom class to the LinkedHashSet and we will implement the equals() and hashCode() methods in a user defined class.

CopiedCopy Code
import java.util.Iterator;
import java.util.LinkedHashSet;
public class LinkedHashSetCustomElements {
	public static void main(String[] args) {
		//Creating LinkedHashSet object with default capacity and load factor  
        LinkedHashSet<Student> linkedset=new LinkedHashSet<Student>(); 
		Student std1 = new Student("A1","Higher Grade School");
		Student std2 = new Student("A2","Higher Grade School");
		Student std3 = new Student("A3","Higher Grade School");
		Student std4 = new Student("A4","Higher Grade School");
		Student std5 = new Student("A2","Higher Grade School");
		linkedset.add(std1);
		linkedset.add(std2);
		linkedset.add(std3);
		linkedset.add(std4);
		//printing students set to see order
		System.out.println("Student Elements :"+linkedset);
		//trying to add duplicate student details to the set
		linkedset.add(std5);
		//printing students set to see order changed
		System.out.println("Student Elements after trying add duplicate element:"+linkedset);
		//remove student whose ID is A3
		linkedset.remove(std3);
		System.out.println("Student Elements after removing:"+linkedset);
	}
	static class Student {
		public String stdId;
		public String schoolName;
		public Student(String stdId, String schoolName) {
			this.stdId = stdId;
			this.schoolName = schoolName;
		}
		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + ((stdId == null) ? 0 : stdId.hashCode());
			return result;
		}
		@Override
		public boolean equals(Object obj) {
			Student other = (Student) obj;
			if (stdId.equals(other.stdId))
				return true;
			return false;
		}
		@Override
		public String toString() {
			return "Student [stdId=" + stdId + ", schoolName=" + schoolName + "]";
		}
	}
}

Output :

Student Elements :[Student [stdId=A1, schoolName=Higher Grade School], Student [stdId=A2, schoolName=Higher Grade School], Student [stdId=A3, schoolName=Higher Grade School], Student [stdId=A4, schoolName=Higher Grade School]]
Student Elements after trying add duplicate element:[Student [stdId=A1, schoolName=Higher Grade School], Student [stdId=A2, schoolName=Higher Grade School], Student [stdId=A3, schoolName=Higher Grade School], Student [stdId=A4, schoolName=Higher Grade School]]
Student Elements after removing:[Student [stdId=A1, schoolName=Higher Grade School], Student [stdId=A2, schoolName=Higher Grade School], Student [stdId=A4, schoolName=Higher Grade School]]

Explanation:

In the above example, created a user-defined class Student with overriding methods of equals() and hashCode(). Added four unique elements and after tried to add duplicate element to check any change in insertion order. Removed one element in middle of the LinkedHashSet and printed all the elements to check any insertion order changed.

Note:

In the above example, we created user-defined class inner class but no compulsion to create a class inside of another class.

Conclusion:

In this tutorial, we have covered what is the LinkedHashSet, along with uses and covered two working examples one with user-defined class elements.