LinkedHashSet

A LinkedHashSet in Java is an implementation of the Set interface that maintains insertion order of elements, which means when you iterate through a LinkedHashSet, the elements are returned in the order they were inserted. It combines the uniqueness property of HashSet with predictable iteration order provided by a linked list.

import java.util.LinkedHashSet;

// Syntax for creating a LinkedHashSet
LinkedHashSet<Type> setName = new LinkedHashSet<>();Code language: JavaScript (javascript)

Constructors

Constructor Description
LinkedHashSet() Creates an empty set with default capacity and load factor.
LinkedHashSet(int initialCapacity) Creates with specified capacity.
LinkedHashSet(int initialCapacity, float loadFactor) Specifies capacity and load factor.
LinkedHashSet(Collection<? extends E> c) Creates a set containing elements of the collection.

Commonly Used Methods

LinkedHashSet inherits methods from HashSet, which in turn inherits from AbstractSet, Set, Collection, and Iterable.

Basic Set Operations

Method Description
boolean add(E e) Adds element if not present.
boolean remove(Object o) Removes specified element.
boolean contains(Object o) Checks if element exists.
void clear() Removes all elements.
int size() Returns number of elements.
boolean isEmpty() Checks if set is empty.
Iterator<E> iterator() Returns iterator (in insertion order).
Object[] toArray() Returns array of elements.
<T> T[] toArray(T[] a) Returns typed array.

Bulk Operations

Method Description
boolean addAll(Collection<? extends E> c) Adds all elements from collection.
boolean containsAll(Collection<?> c) Checks if all elements exist.
boolean removeAll(Collection<?> c) Removes all matching elements.
boolean retainAll(Collection<?> c) Retains only elements also in collection.

Advanced Methods (Java 8+)

Method Description
void forEach(Consumer<? super E> action) Performs action on each element.
boolean removeIf(Predicate<? super E> filter) Removes elements that match condition.
Spliterator<E> spliterator() Returns spliterator for parallel iteration.
Stream<E> stream() Returns sequential stream.
Stream<E> parallelStream() Returns parallel stream.
import java.util.LinkedHashSet;
public class LinkedHashSetExample {
    public static void main(String[] args) {
        // Creating a LinkedHashSet to store student names
        LinkedHashSet<String> studentSet = new LinkedHashSet<>();
        // Adding students to the LinkedHashSet
        studentSet.add("Paani");
        studentSet.add("Mahesh");
        studentSet.add("Datta");
        studentSet.add("Ganesh");
        studentSet.add("Harsha");

        // Attempting to add duplicate student (Mahesh)
        boolean addedDuplicate = studentSet.add("Mahesh");
        System.out.println("Duplicate 'Mahesh' added? " + addedDuplicate);

        // Displaying the set of students
        System.out.println("\nSet of students:");
        for (String student : studentSet) {
            System.out.println(student);
        }

        // Removing a student from the set
        studentSet.remove("Datta");

        // Displaying the updated set
        System.out.println("\nUpdated set of students:");
        for (String student : studentSet) {
            System.out.println(student);
        }

        // Checking if the set contains a student
        String searchStudent = "Harsha";
        boolean containsStudent = studentSet.contains(searchStudent);
        System.out.println("\nDoes the set contain '" + searchStudent + "'? " + containsStudent);

        // Size of the set
        System.out.println("Size of the set: " + studentSet.size());

        // Clearing the set
        studentSet.clear();
        System.out.println("Is the set empty now? " + studentSet.isEmpty());
    }
}

D:\>javac LinkedHashSetExample.java

D:\>java LinkedHashSetExample
Duplicate 'Mahesh' added? false

Set of students:
Paani
Mahesh
Datta
Ganesh
Harsha

Updated set of students:
Paani
Mahesh
Ganesh
Harsha

Does the set contain 'Harsha'? true
Size of the set: 4
Is the set empty now? trueCode language: JavaScript (javascript)

LinkedHashSet in Java combines the uniqueness property of HashSet with the predictable iteration order provided by a linked list. It offers efficient performance for basic operations and guarantees the order of elements based on insertion sequence. Understanding when to use LinkedHashSet based on its features can help in designing effective data structures and algorithms in Java applications.

Scroll to Top