Java Language – 27 – Sets (HashSet, TreeSet, etc.)

Collections and Data Structures – Sets (HashSet, TreeSet, etc.)
Introduction

Sets are an essential part of the Java Collections Framework, allowing you to store unique elements without duplicates. Java provides several set implementations, including ‘HashSet’ and ‘TreeSet.’ In this guide, we’ll explore the concept of sets in Java, understand the differences between ‘HashSet’ and ‘TreeSet,’ and learn how to use them effectively in your Java applications.

HashSet: Unordered Collection

‘HashSet’ is an implementation of the ‘Set’ interface that stores elements in an unordered manner. It does not allow duplicate elements and offers constant-time performance for basic operations like ‘add,’ ‘remove,’ and ‘contains.’

Example – Using HashSet

Here’s an example of creating and using a ‘HashSet’ to store unique names:


import java.util.HashSet;
import java.utilSet;

public class HashSetExample {
    public static void main(String[] args) {
        Set<String> names = new HashSet<>();

        // Adding elements to the HashSet
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");

        // Adding a duplicate element
        names.add("Alice");

        // Iterating through the HashSet
        for (String name : names) {
            System.out.println(name);
        }
    }
}

In this example, we create a ‘HashSet’ of strings to store unique names. Attempting to add a duplicate element (“Alice” in this case) won’t affect the set’s content.

TreeSet: Sorted Collection

‘TreeSet’ is another set implementation in Java that stores elements in sorted order. It uses a Red-Black Tree internally to maintain elements in ascending order. ‘TreeSet’ also does not allow duplicates.

Example – Using TreeSet

Here’s an example of creating and using a ‘TreeSet’ to store unique numbers in sorted order:


import java.util.TreeSet;
import java.utilSet;

public class TreeSetExample {
    public static void main(String[] args) {
        Set<Integer> numbers = new TreeSet<>();

        // Adding elements to the TreeSet
        numbers.add(3);
        numbers.add(1);
        numbers.add(2);

        // Adding a duplicate element
        numbers.add(1);

        // Iterating through the TreeSet
        for (int number : numbers) {
            System.out.println(number);
        }
    }
}

In this example, we create a ‘TreeSet’ of integers to store unique numbers in sorted order. Duplicate elements are automatically removed.

Choosing Between HashSet and TreeSet

When deciding between ‘HashSet’ and ‘TreeSet,’ consider your application’s specific requirements:

  • ‘HashSet’ is a better choice when:
    • You need faster insertion and retrieval of elements.
    • The order of elements does not matter.
    • You don’t need sorted elements.
  • ‘TreeSet’ is a better choice when:
    • You require elements to be stored in sorted order.
    • You need a set of elements in ascending or descending order.
    • You don’t want duplicates, and you’re okay with the additional overhead for maintaining order.
Common Set Operations

Sets provide several common operations for managing elements:

  • Adding Elements: Use the ‘add’ method to add elements to the set. Duplicates are automatically rejected.
  • Removing Elements: Use the ‘remove’ method to delete elements from the set.
  • Checking for Existence: Use the ‘contains’ method to check if an element exists in the set.
  • Iterating: Use ‘for-each’ loops or iterators to traverse the set.
Conclusion

Sets are invaluable data structures in Java for storing unique elements. ‘HashSet’ and ‘TreeSet’ are two commonly used implementations, each offering distinct advantages. By understanding the characteristics and use cases of these sets, you can efficiently manage collections of data in your Java applications.