Java LinkedHashSet

LinkedHashSet in Java is a class in the Java Collections Framework that extends the HashSet class, which implements the Set interface. LinkedHashSet is basically a combination of a HashSet class and a LinkedList class, possessing the characteristics of both.

Key Points About Java LinkedHashSet

Here are some important key points about the LinkedHashSet class in Java: 

Order Preservation: 

LinkedHashSet is a HashSet with a linked list implementation that maintains insertion order. So, when you iterate through elements in a LinkedHashSet, they will be returned in the order in which they were inserted. 

Null elements: 

LinkedHashSet allows one null element. 

No Duplicates: 

Just like HashSet, LinkedHashSet also does not allow duplicate elements. That is, you can only store unique elements in a LinkedHashSet. 

Non-synchronized: 

LinkedHashSet is not synchronized (i.e., it is not thread-safe). This means that multiple threads can access and modify a LinkedHashSet concurrently. If you need to use a thread-safe Set implementation in a multi-threaded environment, consider using Collections.synchronizedSet() or ConcurrentHashMap.

Performance: 

LinkedHashSet offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. 

Uses: 

It is useful when you want to maintain the order of elements (based on insertion order) but also want to avoid duplicates. 

Iteration: 

The iterator provided by LinkedHashSet runs at a predictable pace, which can be advantageous over the random pace of HashSet when a consistent iteration speed is required. 

Inherits from HashSet: 

LinkedHashSet is part of the Java Collections Framework and extends the HashSet class which in turn implements Set, Cloneable, and Serializable interfaces.

Create LinkedHashSet and Add Elements to It

Let's write a program that creates a LinkedHashSet and adds some elements to it.
// Import the necessary class from the Java Collections Framework
import java.util.LinkedHashSet;

public class LinkedHashSetExample {
    public static void main(String args[]) {
        // Create a new LinkedHashSet of strings
        LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();

        // Add elements to the LinkedHashSet
        linkedHashSet.add("Apple");
        linkedHashSet.add("Orange");
        linkedHashSet.add("Banana");
        linkedHashSet.add("Pineapple");
        linkedHashSet.add("Apple"); // This will not be inserted as "Apple" is already present in the set

        // Try to add a null value
        linkedHashSet.add(null);
        linkedHashSet.add(null); // This will not be inserted as null is already present in the set

        // Print the LinkedHashSet
        System.out.println(linkedHashSet); // Outputs: [Apple, Orange, Banana, Pineapple, null]
    }
}

Output:

[Apple, Orange, Banana, Pineapple, null]
This code creates a LinkedHashSet and adds some elements to it. It tries to add the element "Apple" and null twice, but as LinkedHashSet cannot contain duplicate elements, these are not added. When the LinkedHashSet is printed out, it retains the order of the elements as they were first added, and does not include any duplicates.

Access Elements from LinkedHashSet

LinkedHashSet does not provide a get method like the List interface to access elements directly using the index because it is not an indexed Collection. 

However, you can access the elements of a LinkedHashSet by using an iterator or a for-each loop. Here's how you can access elements in a LinkedHashSet:

/ Import the necessary classes
import java.util.LinkedHashSet;
import java.util.Iterator;

public class LinkedHashSetExample {
    public static void main(String args[]) {
        // Create a new LinkedHashSet of strings
        LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();

        // Add elements to the LinkedHashSet
        linkedHashSet.add("Apple");
        linkedHashSet.add("Orange");
        linkedHashSet.add("Banana");
        linkedHashSet.add("Pineapple");

        // Create an iterator
        Iterator<String> iterator = linkedHashSet.iterator();

        // Print the LinkedHashSet using the iterator
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        
        // Alternatively, you can also use the for-each loop to access elements
        System.out.println("\nIterating using for-each loop: ");
        for(String fruit : linkedHashSet) {
            System.out.println(fruit);
        }
    }
}

Output:

Apple
Orange
Banana
Pineapple

Iterating using for-each loop: 
Apple
Orange
Banana
Pineapple

Removing Elements from LinkedHashSet

LinkedHashSet class provides remove() and clear() methods to remove one or more elements from the LinkedHashSet.
// Import the necessary classes
import java.util.LinkedHashSet;

public class LinkedHashSetExample {
    public static void main(String args[]) {
        // Create a new LinkedHashSet of strings
        LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();

        // Add elements to the LinkedHashSet
        linkedHashSet.add("Apple");
        linkedHashSet.add("Orange");
        linkedHashSet.add("Banana");
        linkedHashSet.add("Pineapple");

        // Print the original LinkedHashSet
        System.out.println("Original LinkedHashSet: " + linkedHashSet);

        // Remove the "Orange" element
        linkedHashSet.remove("Orange");

        // Print the LinkedHashSet after removing "Orange"
        System.out.println("LinkedHashSet after removing Orange: " + linkedHashSet);

        // If you try to remove an element which does not exist, it will not throw an error.
        // It will simply return false.
        boolean isRemoved = linkedHashSet.remove("Grapes");
        System.out.println("Is Grapes removed: " + isRemoved);

        // Clear all elements from the LinkedHashSet
        linkedHashSet.clear();

        // Print the LinkedHashSet after clearing all elements
        System.out.println("LinkedHashSet after clearing all elements: " + linkedHashSet);
    }
}

Output:

Original LinkedHashSet: [Apple, Orange, Banana, Pineapple]
LinkedHashSet after removing Orange: [Apple, Banana, Pineapple]
Is Grapes removed: false
LinkedHashSet after clearing all elements: []

Search Elements in LinkedHashSet

We can use contains() method to check if the LinkedHashSet contains a specific element.

Here is the complete example to search elements in a LinkedHashSet:
// Import the necessary classes
import java.util.LinkedHashSet;

public class LinkedHashSetSearch {
    public static void main(String[] args) {
        // Create a LinkedHashSet
        LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();

        // Add elements to LinkedHashSet
        linkedHashSet.add("Apple");
        linkedHashSet.add("Orange");
        linkedHashSet.add("Banana");
        linkedHashSet.add("Pineapple");

        // Display the LinkedHashSet
        System.out.println("LinkedHashSet: " + linkedHashSet);

        // Check if the LinkedHashSet contains "Apple"
        boolean found = linkedHashSet.contains("Apple");
        System.out.println("Is Apple in the LinkedHashSet? " + found);

        // Check if the LinkedHashSet contains "Grapes"
        found = linkedHashSet.contains("Grapes");
        System.out.println("Is Grapes in the LinkedHashSet? " + found);
    }
}

Output:

LinkedHashSet: [Apple, Orange, Banana, Pineapple]
Is Apple in the LinkedHashSet? true
Is Grapes in the LinkedHashSet? false

Iterating over LinkedHashSet

Iterating over a LinkedHashSet in Java can be done in several ways, including using an iterator, a for-each loop, and Java 8's forEach method.

Using an Iterator

Iterator<String> iterator = linkedHashSet.iterator();
while(iterator.hasNext()) {
    String element = iterator.next();
    System.out.println(element);
}

Using a for-each loop

for(String element : linkedHashSet) {
    System.out.println(element);
}

Using Java 8's forEach method

linkedHashSet.forEach(element -> {
    System.out.println(element);
});

Using Java 8's Stream API

linkedHashSet.stream().forEach(System.out::println);

Complete Example

Let's write a complete Java program where we will create a LinkedHashSet of Strings, add elements to it, and then iterate over the LinkedHashSet using different ways:
import java.util.LinkedHashSet;
import java.util.Iterator;

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

        // Add elements to the LinkedHashSet
        linkedHashSet.add("Apple");
        linkedHashSet.add("Banana");
        linkedHashSet.add("Cherry");

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

        // Using for-each loop
        System.out.println("\nIterating using for-each loop:");
        for(String element : linkedHashSet) {
            System.out.println(element);
        }

        // Using Java 8's forEach method
        System.out.println("\nIterating using Java 8's forEach method:");
        linkedHashSet.forEach(element -> {
            System.out.println(element);
        });

        // Using Java 8's Stream API
        System.out.println("\nIterating using Java 8's Stream API:");
        linkedHashSet.stream().forEach(System.out::println);
    }
}

Output:

Iterating using Iterator:
Apple
Banana
Cherry

Iterating using for-each loop:
Apple
Banana
Cherry

Iterating using Java 8's forEach method:
Apple
Banana
Cherry

Iterating using Java 8's Stream API:
Apple
Banana
Cherry

LinkedHashSet with User defined objects

This example shows how to create a LinkedHashSet of user-defined objects and it maintains insertion order.

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

class Customer {
    private long id;
    private String name;

    public Customer(long id, String name) {
        this.id = id;
        this.name = name;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    // Two customers are equal if their IDs are equal
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Customer customer = (Customer) o;
        return id == customer.id;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

public class HashSetUserDefinedObjectExample {
    public static void main(String[] args) {
        Set<Customer> customers = new LinkedHashSet<>();
        customers.add(new Customer(101, "Ramesh"));
        customers.add(new Customer(102, "Umesh"));
        customers.add(new Customer(103, "Rajkumar"));

        System.out.println(customers);
    }
}

Conclusion

In this article, we have learned what is LinkedHashSet, how to create and add elements to LinkedHashSet, how to access elements from LinkedHashSet, how to remove elements from LinkedHashSet, how to search elements in LinkedHashSet, how to iterate over LinkedHashSet, and how to work with user-objects.

Comments