Java LinkedHashSet Tutorial with Examples

LinkedHashSet is a part of the Java Collections Framework and provides a hash table and linked list implementation of the Set interface. It maintains a doubly-linked list running through all its entries, thus maintaining the insertion order. This tutorial will cover all methods of LinkedHashSet with examples and outputs, highlighting key points, use cases, best practices, performance considerations, and a real-time example with CRUD operations.

Table of Contents

  1. Introduction
  2. Key Points
  3. LinkedHashSet Methods
    • add()
    • addAll()
    • remove()
    • clear()
    • size()
    • isEmpty()
    • contains()
    • iterator()
    • removeIf()
    • toArray()
  4. Use Cases
  5. Best Practices
  6. Performance Considerations
  7. Real-time Example with CRUD Operations
  8. Conclusion

1. Introduction

A LinkedHashSet in Java is a part of the Java Collections Framework and provides a way to store unique elements while maintaining the order of insertion. It is found in the java.util package and is backed by a hash table and a linked list, which allows for fast access to elements and maintains the order in which elements are inserted.

2. Key Points

  • LinkedHashSet does not allow duplicate elements.
  • It maintains the insertion order.
  • It allows null values.
  • It is not synchronized.
  • It provides constant-time performance for basic operations like add, remove, and contains.

3. LinkedHashSet Methods

3.1. add()

The add() method is used to insert elements into the LinkedHashSet.

Example:

import java.util.LinkedHashSet;

public class LinkedHashSetExample {
    public static void main(String[] args) {
        LinkedHashSet<String> fruits = new LinkedHashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");
        System.out.println(fruits);
    }
}

Output:

[Apple, Banana, Mango]

3.2. addAll()

The addAll() method adds all elements of a collection to the LinkedHashSet.

Example:

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

public class LinkedHashSetExample {
    public static void main(String[] args) {
        LinkedHashSet<String> fruits = new LinkedHashSet<>();
        fruits.add("Apple");
        fruits.addAll(Arrays.asList("Banana", "Mango"));
        System.out.println(fruits);
    }
}

Output:

[Apple, Banana, Mango]

3.3. remove()

The remove() method removes the specified element from the LinkedHashSet.

Example:

import java.util.LinkedHashSet;

public class LinkedHashSetExample {
    public static void main(String[] args) {
        LinkedHashSet<String> fruits = new LinkedHashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");
        fruits.remove("Banana");
        System.out.println(fruits); // [Apple, Mango]
    }
}

Output:

[Apple, Mango]

3.4. clear()

The clear() method removes all elements from the LinkedHashSet.

Example:

import java.util.LinkedHashSet;

public class LinkedHashSetExample {
    public static void main(String[] args) {
        LinkedHashSet<String> fruits = new LinkedHashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");
        fruits.clear();
        System.out.println(fruits); // []
    }
}

Output:

[]

3.5. size()

The size() method returns the number of elements in the LinkedHashSet.

Example:

import java.util.LinkedHashSet;

public class LinkedHashSetExample {
    public static void main(String[] args) {
        LinkedHashSet<String> fruits = new LinkedHashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");
        System.out.println(fruits.size()); // 3
    }
}

Output:

3

3.6. isEmpty()

The isEmpty() method checks if the LinkedHashSet is empty.

Example:

import java.util.LinkedHashSet;

public class LinkedHashSetExample {
    public static void main(String[] args) {
        LinkedHashSet<String> fruits = new LinkedHashSet<>();
        System.out.println(fruits.isEmpty()); // true
        fruits.add("Apple");
        System.out.println(fruits.isEmpty()); // false
    }
}

Output:

true
false

3.7. contains()

The contains() method checks if the LinkedHashSet contains a specified element.

Example:

import java.util.LinkedHashSet;

public class LinkedHashSetExample {
    public static void main(String[] args) {
        LinkedHashSet<String> fruits = new LinkedHashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        System.out.println(fruits.contains("Banana")); // true
        System.out.println(fruits.contains("Mango")); // false
    }
}

Output:

true
false

3.8. iterator()

The iterator() method returns an iterator for the elements in the LinkedHashSet.

Example:

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

public class LinkedHashSetExample {
    public static void main(String[] args) {
        LinkedHashSet<String> fruits = new LinkedHashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");
        Iterator<String> iterator = fruits.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

Output:

Apple
Banana
Mango

3.9. removeIf()

The removeIf() method removes all elements of the LinkedHashSet that satisfy the given predicate.

Example:

import java.util.LinkedHashSet;

public class LinkedHashSetExample {
    public static void main(String[] args) {
        LinkedHashSet<String> fruits = new LinkedHashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");
        fruits.removeIf(fruit -> fruit.startsWith("A"));
        System.out.println(fruits); // [Banana, Mango]
    }
}

Output:

[Banana, Mango]

3.10. toArray()

The toArray() method converts the LinkedHashSet into an array.

Example:

import java.util.LinkedHashSet;

public class LinkedHashSetExample {
    public static void main(String[] args) {
        LinkedHashSet<String> fruits = new LinkedHashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");
        String[] fruitsArray = fruits.toArray(new String[0]);
        for (String fruit : fruitsArray) {
            System.out.println(fruit);
        }
    }
}

Output:

Apple
Banana
Mango

4. Use Cases

  • Unique collections with order: LinkedHashSet is used when you need a collection of unique elements that maintains insertion order.
  • Cache implementation: It can be used in scenarios where the order of elements is important, such as maintaining a cache.
  • Removing duplicates while maintaining order: It is useful for removing duplicates from a collection while maintaining the order of elements.

5. Best Practices

  • Use appropriate initial capacity: If the size of the set is known in advance, setting an initial capacity can improve performance.
  • Avoid frequent traversals: Iterating over a LinkedHashSet is not as fast as iterating over an ArrayList due to its linked list structure.
  • Use HashSet if order is not important: If insertion order is not important, consider using HashSet for slightly better performance.

6. Performance Considerations

  • Constant-time performance: LinkedHashSet provides constant-time performance for basic operations like add, remove, and contains.
  • Memory usage: Each element in a LinkedHashSet requires additional memory for storing hash codes and pointers.
  • Thread safety: LinkedHashSet is not synchronized. Use Collections.synchronizedSet() if thread safety is needed.

7. Real-time Example with CRUD Operations

Managing a Product Set:

Product.java:

public class Product {
    private String name;
    private double price;

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

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

    @Override
    public int hashCode() {
        return name.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Product product = (



Product) obj;
        return Double.compare(product.price, price) == 0 && name.equals(product.name);
    }
}

Main.java:

import java.util.LinkedHashSet;

public class Main {
    public static void main(String[] args) {
        LinkedHashSet<Product> productSet = new LinkedHashSet<>();

        // Create
        productSet.add(new Product("Laptop", 1200.00));
        productSet.add(new Product("Smartphone", 800.00));
        productSet.add(new Product("Tablet", 300.00));

        // Read
        for (Product product : productSet) {
            System.out.println(product);
        }

        // Update
        productSet.remove(new Product("Smartphone", 800.00));
        productSet.add(new Product("Smartphone", 850.00));
        System.out.println("After Update:");
        for (Product product : productSet) {
            System.out.println(product);
        }

        // Delete
        productSet.remove(new Product("Laptop", 1200.00));
        System.out.println("After Deletion:");
        for (Product product : productSet) {
            System.out.println(product);
        }
    }
}

Output:

Product{name='Laptop', price=1200.0}
Product{name='Smartphone', price=800.0}
Product{name='Tablet', price=300.0}
After Update:
Product{name='Laptop', price=1200.0}
Product{name='Smartphone', price=850.0}
Product{name='Tablet', price=300.0}
After Deletion:
Product{name='Smartphone', price=850.0}
Product{name='Tablet', price=300.0}

8. Conclusion

The LinkedHashSet class in Java for managing unique collections of elements while maintaining insertion order. By understanding its methods, use cases, and best practices, you can effectively utilize LinkedHashSet in your Java applications. This tutorial covers the essential methods with examples and demonstrates a real-time example with CRUD operations.

Comments