• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

LinkedHashSet in Java with Code and Examples

Irfan Khan/66/0
CodeJAVA

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.

Table of Contents

  • Creating LinkedHashSet in Java
  • Adding Elements to the LinkedHashSet
  • Removing Elements from LinkedHashSet
  • Traversing Elements in LinkedHashSet
  • Searching Elements in LinkedHashSet
  • LinkedHashSet Spliterator
  • Methods for Set 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.

Java
Irfan Khan
I’m a software programmer having more than 5 years of development experience in Java and related technology. I write technical content as well and love to share the technical knowledge to make it available for all.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Leave a Reply Cancel reply

Basic Java Tutorial

  1. Java- Tutorial Overview
  2. Java- Features & Characteristics
  3. Java-  Installation & Setup
  4. Java- Hello, World Program!
  5. Java- JDK vs JVM vs JRE
  6. Java- Data Types & Variables
  7. Java- String & its Methods
  8. Java- Different Operators Types
  9. Java- Flow Control Statements
  10. Java- Array
  11. Java- Exception Handling
  12. Java- ‘throw’ vs ‘throws’ Keyword
  13. Java- RegEx
  14. Java 12- New Advanced Features

Java OOPs concepts

  1. Java- OOPs Introduction
  2. Java- Classes & Objects
  3. Java- Constructor & Overloading
  4. Java- Method Overload vs Override
  5. Java- Access Modifiers
  6. Java- Abstraction
  7. Java- Inheritance
  8. Java- Interfaces
  9. Java- Nested Inner Classes

Java Advanced

  1. Java- Applet vs Application
  2. Java- HashMap Collections
  3. Java- ArrayList
  4. Java- LinkedList
  5. Java- Reverse Linked List
  6. Java- HashSet
  7. Java- HashMap vs HashSet
  8. Java-LinkedHashSet 

Java Exercise

50+ Java Coding Questions [Practice]

Java Projects

Patient Billing Software

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard