Home page

Tuesday, June 13, 2023

LinkedHashSet in JAVA

A LinkedHashSet in Java is a data structure that combines the features of both a HashSet and a LinkedList. It maintains a linked list of the entries in the set, which allows for predictable iteration order, while also providing constant-time complexity for the basic operations (add, remove, contains).

You can use a LinkedHashSet in situations where you need to maintain the order of insertion of elements, along with the uniqueness of elements. Some common use cases for LinkedHashSet include:

Preserving insertion order: If you need to iterate over the elements of a set in the order they were inserted, a LinkedHashSet can be used.

Removing duplicates while preserving order: If you have a collection of elements where duplicates need to be eliminated but the order of the remaining elements must be maintained, a LinkedHashSet can be used.

Here's an example of how you can use a LinkedHashSet in Java:

import java.util.LinkedHashSet;

public class LinkedHashSetExample {

    public static void main(String[] args) {

        LinkedHashSet<String> set = new LinkedHashSet<>();

        // Adding elements to the LinkedHashSet

        set.add("Apple");

        set.add("Banana");

        set.add("Orange");

        set.add("Apple"); // Duplicate entry, will be ignored

        // Iterating over the elements in the LinkedHashSet

        for (String element : set) {

            System.out.println(element);

        }

        // Checking if an element exists in the LinkedHashSet

        boolean containsBanana = set.contains("Banana");

        System.out.println("Contains Banana? " + containsBanana);

        // Removing an element from the LinkedHashSet

        boolean removed = set.remove("Orange");

        System.out.println("Removed Orange? " + removed);

        // Size of the LinkedHashSet

        System.out.println("Size of LinkedHashSet: " + set.size());

    }

}

In this example, we create a LinkedHashSet called set to store strings.

We add elements to the set using the add() method. Note that the duplicate entry of "Apple" is ignored, as LinkedHashSet does not allow duplicate elements.

We iterate over the elements of the set using a for-each loop and print each element.

We check if an element exists in the set using the contains() method.

We remove an element from the set using the remove() method and store the result in a boolean variable.

Finally, we print the size of the set using the size() method.

Output:
Apple
Banana
Orange
Contains Banana? true
Removed Orange? true
Size of LinkedHashSet: 2

No comments:

Post a Comment