Java LinkedHashSet

Ramesh Fadatare
5 min readSep 19, 2024

--

Introduction

Welcome to the Java Collections framework tutorial series. In this tutorial, we will learn everything about the LinkedHashSet class in Java.

LinkedHashSet in Java is a part of the Java Collections Framework and implements the Set interface. It is a hash table and linked list implementation of the Set interface, with predictable iteration order. It maintains a doubly-linked list running through all of its entries, which defines the iteration order as the order in which elements were inserted.

Learn complete Java programming: https://www.rameshfadatare.com/learn-java-programming/

Table of Contents

  1. What is LinkedHashSet?
  2. Key Points About LinkedHashSet
  3. Creating a LinkedHashSet and Adding Elements
  4. Accessing Elements in a LinkedHashSet
  5. Removing Elements from a LinkedHashSet
  6. Iterating Over a LinkedHashSet
  7. Searching for Elements in a LinkedHashSet
  8. LinkedHashSet of User-Defined Objects
  9. Common LinkedHashSet Methods
  10. Conclusion

1. What is LinkedHashSet?

A LinkedHashSet is a hash table and linked list implementation of the Set interface. It maintains a doubly-linked list running through all of its entries, which defines the iteration order. The iteration order is the order in which elements were inserted into the set (insertion-order).

2. Key Points About LinkedHashSet

  • No Duplicates: Does not allow duplicate elements.
  • Null Elements: Allows null elements.
  • Insertion Order: Maintains the order of elements as they were inserted.
  • Hashing: Uses hash table for storage.
  • Performance: Provides constant-time performance for basic operations like add, remove, contains, and size, with additional overhead to maintain the linked list.

3. Creating a LinkedHashSet and Adding Elements

To create a LinkedHashSet, you can use the LinkedHashSet constructor. You can then use methods such as add to add elements to the set.

Example:

In this example, we create a LinkedHashSet of strings and add a few elements to it.

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

public class LinkedHashSetExample {
public static void main(String[] args) {
// Creating a LinkedHashSet
Set<String> fruits = new LinkedHashSet<>();

// Adding elements to the LinkedHashSet
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
fruits.add("Apple"); // Duplicate element

// Displaying the LinkedHashSet
System.out.println("LinkedHashSet: " + fruits);
}
}

Output:

LinkedHashSet: [Apple, Banana, Cherry]

4. Accessing Elements in a LinkedHashSet

You can check for the presence of an element in a LinkedHashSet using the contains method.

Example:

In this example, we demonstrate how to check if an element exists in a LinkedHashSet.

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

public class AccessLinkedHashSet {
public static void main(String[] args) {
// Creating a LinkedHashSet
Set<String> fruits = new LinkedHashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");

// Checking for the presence of an element
System.out.println("Does the LinkedHashSet contain 'Banana'? " + fruits.contains("Banana"));
System.out.println("Does the LinkedHashSet contain 'Mango'? " + fruits.contains("Mango"));
}
}

Output:

Does the LinkedHashSet contain 'Banana'? true
Does the LinkedHashSet contain 'Mango'? false

5. Removing Elements from a LinkedHashSet

You can remove elements from a LinkedHashSet using methods such as remove and clear.

Example:

In this example, we demonstrate how to remove elements from a LinkedHashSet.

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

public class RemoveLinkedHashSet {
public static void main(String[] args) {
// Creating a LinkedHashSet
Set<String> fruits = new LinkedHashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");

// Removing an element
fruits.remove("Banana");

// Displaying the LinkedHashSet after removal
System.out.println("LinkedHashSet after removal: " + fruits);

// Clearing the LinkedHashSet
fruits.clear();
System.out.println("LinkedHashSet after clearing: " + fruits);
}
}

Output:

LinkedHashSet after removal: [Apple, Cherry]
LinkedHashSet after clearing: []

6. Iterating Over a LinkedHashSet

You can iterate over a LinkedHashSet using various methods such as a simple for-each loop and iterator.

Example:

In this example, we demonstrate different ways to iterate over a LinkedHashSet.

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

public class IterateLinkedHashSet {
public static void main(String[] args) {
// Creating a LinkedHashSet
Set<String> fruits = new LinkedHashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");

// Using simple for-each loop
System.out.println("Using simple for-each loop:");
for (String fruit : fruits) {
System.out.println(fruit);
}

// Using iterator
System.out.println("Using iterator:");
Iterator<String> iterator = fruits.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}

Output:

Using simple for-each loop:
Apple
Banana
Cherry
Using iterator:
Apple
Banana
Cherry

7. Searching for Elements in a LinkedHashSet

You can search for elements in a LinkedHashSet using the contains method.

Example:

In this example, we demonstrate how to check if a LinkedHashSet contains a given element.

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

public class SearchLinkedHashSet {
public static void main(String[] args) {
// Creating a LinkedHashSet
Set<String> fruits = new LinkedHashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");

// Check if the LinkedHashSet contains a given element
System.out.println("Does the LinkedHashSet contain 'Banana'? " + fruits.contains("Banana"));
System.out.println("Does the LinkedHashSet contain 'Mango'? " + fruits.contains("Mango"));
}
}

Output:

Does the LinkedHashSet contain 'Banana'? true
Does the LinkedHashSet contain 'Mango'? false

8. LinkedHashSet of User-Defined Objects

You can use LinkedHashSet to store user-defined objects. This involves creating a class for the objects you want to store and ensuring that the equals and hashCode methods are properly overridden.

Example:

In this example, we create a Person class and then create a LinkedHashSet to store Person objects.

import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;

class Person {
private String name;
private int age;

public Person(String name, int age) {
this.name = name;
this.age = age;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}

@Override
public int hashCode() {
return Objects.hash(name, age);
}

@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}

public class UserDefinedObjectLinkedHashSet {
public static void main(String[] args) {
// Creating a LinkedHashSet of Person objects
Set<Person> people = new LinkedHashSet<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));

// Displaying the LinkedHashSet
System.out.println("LinkedHashSet of Person objects: " + people);
}
}

Output:

LinkedHashSet of Person objects: [Person{name='Alice', age=30}, Person{name='Bob', age=25}, Person{name='Charlie', age=35}]

9. All LinkedHashSet Class Methods

10. Conclusion

LinkedHashSet is a versatile collection class in Java that combines the unique element storage capabilities of a HashSet with the predictable iteration order of a linked list. It is useful in scenarios where you need to maintain the order of elements as they were inserted while still ensuring that no duplicates are present.

Understanding how to create, manipulate, and iterate over LinkedHashSet can help you effectively manage collections of unique objects in your Java applications.

Original Post:

https://www.rameshfadatare.com/java-programming/java-linkedhashset/

--

--

No responses yet