LinkedHashSet in Java with Code and Examples

LinkedHashSet in Java with Code and Examples

In Java, a LinkedHashSet is a class that implements the Set interface and is based on a linked list data structure. It maintains the elements in the order they were added, and also provides fast access to the elements.

It is similar to a HashSet, but it also maintains a doubly-linked list running through all of its entries. This linked list defines the iteration order, which is normally the order in which elements were inserted into the set (insertion-order).

This class is useful if you want to maintain insertion order or access frequently because it provides O(1) the time complexity for insertion, search, and deletion operations.

Creating LinkedHashSet in Java

To create LinkedHashSet, we can use any of the below constructors such as:

LinkedHashSet()

It creates a new, empty linked hash set with the default initial capacity (16) and load factor (0.75).

LinkedHashSet(int initialCapacity)

It creates a new one with the specified initial capacity and the default load factor.

LinkedHashSet(int initialCapacity, float loadFactor)

It creates a new inked hash set with the specified initial capacity and load factor as arguments.

LinkedHashSet(Collection<? extends E> c)

It creates a new linked hash set with the same elements as the specified collection.

In the code below, we created LinkedHashSet objects by using all the available constructors. You can check the below code and output.

package javaexample;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

class MainClass {
	
	public static void main(String[] args) {
	
		// Create empty set
		Set<String> set = new LinkedHashSet<>();
		System.out.println(set);
		
		// Create set with existing collection
		Set<String> set2 = new LinkedHashSet<>(Arrays.asList("One","Two","Three","One"));
		System.out.println(set2);
		
		// Create set with specified initial capacity
		Set<String> set3 = new LinkedHashSet<>(20);
		System.out.println(set3);
	
		// Create set with initial capacity and load factor
		Set<String> set4 = new LinkedHashSet<>(20,1);
		System.out.println(set4);
	}	
}

Output:

[]
[One, Two, Three]
[]
[]

Adding Elements to the LinkedHashSet

In Java, adding elements to a LinkedHashSet is done using the add() method. This method takes an object as a parameter and adds it to the set.

If the set already contains the element, the method will not add it again and will return false. Here is an example of how to add elements to a LinkedHashSet.

You can also add elements to a LinkedHashSet using the addAll() method, which takes a Collection as a parameter and adds all of its elements to the set.

package javaexample;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

class MainClass {
	
	public static void main(String[] args) {
	
		// Create a set
		Set<String> set = new LinkedHashSet<>();
		System.out.println(set);
		
		// Adding elements
		set.add("One");
		set.add("Two");
		set.add("Three");
		set.add("One");
		
		System.out.println(set);
		
		// Add all from existing collection
		List<String> list = Arrays.asList("Five","Six","Two");
		set.addAll(list);
		System.out.println(set);
	}	
}

Output:

[]
[One, Two, Three]
[One, Two, Three, Five, Six]

Removing Elements from LinkedHashSet

In Java, removing elements from a LinkedHashSet is done using the remove() method. This method takes an object as a parameter and removes it from the set, if it is present. If the set does not contain the element, the method will do nothing and return false. Here is an example of how to remove an element from a LinkedHashSet.

You can also remove elements of a LinkedHashSet using the removeIf() method, which is a functional method that takes a predicate as a parameter and removes all elements that match the predicate.

package javaexample;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

class MainClass {
	
	public static void main(String[] args) {
	
		// Create a set
		Set<String> set = new LinkedHashSet<>(Arrays.asList("One","Two","Three","One","Seven"));
		System.out.println(set);
		
		// Remove single element
		set.remove("Three");
		System.out.println(set);
		
		// Remove element if string length is more than 5
		set.removeIf(str->(str.length() >= 5));
		System.out.println(set);
		
		// Remove All elements
		set.removeAll(set);
		System.out.println(set);
				
	}	
}

Output:

[One, Two, Three, Seven]
[One, Two, Seven]
[One, Two]
[]

Traversing Elements in LinkedHashSet

There are several ways to traverse the elements of a LinkedHashSet such as:

A LinkedHashSet is an Iterable, so you can use the iterator() method to get an Iterator and then use the hasNext() and next() methods to traverse the elements as we did in the below code.

Similarly, we can also use the for-each loop to traverse the elements of a LinkedHashSet. See the below code.

package javaexample;

import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

class MainClass {
	
	public static void main(String[] args) {
	
		// Create a set
		Set<String> set = new LinkedHashSet<>(Arrays.asList("One","Two","Three","One","Seven"));
		System.out.println(set);
		
		// print all element
		set.remove("Three");
		System.out.println(set);
		
		// print using the foreach loop
		System.out.println("-------Traverse using the foreach loop-------");
		for (String el : set) {
			System.out.println(el);
		}		
		
		// print using iterator
		System.out.println("----------Traverse using iterator-----------");
		for (Iterator iterator = set.iterator(); iterator.hasNext();) {
			String el = (String) iterator.next();
			System.out.println(el);
			
		}
	}	
}

Output:

[One, Two, Three, Seven]
[One, Two, Seven]
-------Traverse using the foreach loop-------
One
Two
Seven
----------Traverse using iterator-----------
One
Two
Seven

Checking the equality of the set

package javaexample;

import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

class MainClass {
	
	public static void main(String[] args) {
	
		// Create a set
		Set<String> set = new LinkedHashSet<>(Arrays.asList("One","Two","Three","One","Seven"));
		System.out.println(set);
		
		// Create a set
		Set<String> set2 = new LinkedHashSet<>(Arrays.asList("One","Two","Three","One","Seven"));
		System.out.println(set);
		
		if(set.equals(set2)) {
			System.out.println("equal");
		}else {
			System.out.println("not equal");
		}
		
		set.add("Ten"); // Updating the first set
		
		if(set.equals(set2)) {
			System.out.println("equal");
		}else {
			System.out.println("not equal");
		}
		
	}	
}

Output:

[One, Two, Three, Seven]
[One, Two, Three, Seven]
equal
not equal

Searching Elements in LinkedHashSet

In Java, searching for elements in a LinkedHashSet can be done using the contains() method. This method takes an object as a parameter and returns a boolean value indicating whether the set contains the object.

Here is an example of how to search for an element in a LinkedHashSet:

package javaexample;

import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

class MainClass {
	
	public static void main(String[] args) {
	
		// Create a set
		Set<String> set = new LinkedHashSet<>(Arrays.asList("One","Two","Three","One","Seven"));
		System.out.println(set);
		
		// Finding element
		String el = "Ten";
		boolean result = set.contains(el);
		if(result) {
			System.out.println(el+" is present in the set");
		}else System.out.println(el+" is not present in the set");
 		
		result = set.isEmpty(); // check if set is empty
		if(result) {
			System.out.println("set is empty");
		}else System.out.println("set is not empty");
	}	
}

Output:

[One, Two, Three, Seven]
Ten is not present in the set
set is not empty

LinkedHashSet Spliterator

In Java, a Spliterator (short for “Splittable Iterator”) is a class that allows for the efficient traversal and partitioning of elements in a collection, such as a List or Set. It is similar to an Iterator, but it can also be split into multiple independent iterators that can be used to traverse the same data in parallel.

In the example below, we used the spliterator() method to create Spliterator and used the forEachRemaining() method to traverse the elements.

package javaexample;

import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.Spliterator;

class MainClass {
	
	public static void main(String[] args) {
	
		// Create a set
		Set<String> set = new LinkedHashSet<>(Arrays.asList("One","Two","Three","One","Seven"));
		System.out.println(set);
		
		// Spliterator
		Spliterator<String> spl = set.spliterator();
		
		// Traverse elements
		spl.forEachRemaining(System.out::println);
		
	}	
}

Output:

[One, Two, Three, Seven]
One
Two
Three
Seven

Methods for Set Operations

Since this class implements the set interface, we can use set methods to perform set operations such as retain, contain, etc. For these operations, it provides methods such as retainAll(), and containAll().

package javaexample;

import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.Spliterator;

class MainClass {
	
	public static void main(String[] args) {
	
		// Create a set
		Set<String> set = new LinkedHashSet<>(Arrays.asList("One","Two","Three","One","Seven"));
		System.out.println(set);
		
		Set<String> set2 = new LinkedHashSet<>(Arrays.asList("One","Seven"));
		
		// Check Contains all
		boolean result = set.containsAll(set2);
		if(result) {
			System.out.println("It contains set2 elememts");
		}else System.out.println("It does not contain set2 elements");
		
		// Check retains all
		set.retainAll(set2);		
		System.out.println(set);		
	}	
}

Output:

[One, Two, Three, Seven]
It contains set2 elememts
[One, Seven]

Conclusion

LinkedHashSet class is the implementation of the set with the insertion order. We can use this class to store data in the natural order. It uses a linked list data structure internally to store data. It provides O(1) time complexity for insertion, search, and deletion operations.

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *