Trusted answers to developer questions

What is the LinkedHashSet in Java?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

A LinkedHashSet is an ordered form of HashSet that maintains the iteration order. A normal HashSet has no iteration order whereas, in a LinkedHashSet, elements are sorted according to their insertion order. This class extends the HashSet class.

svg viewer

Syntax

LinkedHashSet<data-type> LnkdHashSet = new LinkedHashSet<data-type>();

Useful methods

By default, Java provides some useful helper functions with the HashSet class. Let’s look at some of them in detail:

1. add(Object obj)

As the name suggests, this function adds elements to the LinkedHashSet (provided that they do not exist in the HashSet prior to insertion).

2. remove(Object obj)

Removes a particular object from the LinkedHashSet.

3. clear()

Removes all of the elements from the LinkedHashSet.

4. contains(Object obj)

Checks whether or not the specific element is present in the LinkedHashSet.

5. size()

​Returns the number of elements currently present in the LinkedHashSet.

6. isEmpty()

Checks whether or not the LinkedHashSet is empty.


Code

Let’s take a look at a simple comparison between a HashSet and a LinkedHashSet. When we insert {1, 2, 4, 3} in the HashSet, it sorts the elements and prints them in a sorted order ( i.e., {1, 2, 3, 4} ). Whereas, in the LinkedHashSet, the elements are printed in the insertion order {1, 2, 4, 3}.

import java.util.HashSet;
class Main {
public static void main(String[] args) {
// Creating HashSet to store String values
HashSet<Integer> hash_set = new HashSet<Integer>();
// Adding elements into HashSet usind add()
hash_set.add(1);
hash_set.add(2);
hash_set.add(4);
hash_set.add(3);
// Displaying the HashSet Unordered
System.out.println("HashSet: " + hash_set);
// Extracting size of HashSet
int size = hash_set.size();
System.out.printf("Size of HashSet is: %d \n", size);
// Remove an element
hash_set.remove(4);
// Display HashSet after removal
System.out.println("HashSet after removal: " + hash_set);
}
}

RELATED TAGS

java
linkedhashset
set
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?