Java Tutorial

Operators

Flow Control

String

Number and Date

Built-in Classes

Array

Class and Object

Inheritance and Polymorphism

Exception Handling

Collections, Generics and Enumerations

Reflection

Input/Output Stream

Annotation

Java Set Collections: HashSet And TreeSet

Java provides two important Set implementations in the Collections framework: HashSet and TreeSet. Both are used to store unique elements, but they differ in how elements are stored and accessed. In this tutorial, we'll explore the differences between HashSet and TreeSet and show examples of their usage.

HashSet

HashSet is an unordered collection that implements the Set interface. It uses a hash table for storing elements, providing fast insertion, deletion, and retrieval of elements. The main characteristics of HashSet are:

  1. It does not maintain any order of elements.
  2. It allows a single null value.
  3. It has an average constant-time performance for basic operations (add, remove, and contains).

Example of using a HashSet:

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

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

        colors.add("Red");
        colors.add("Blue");
        colors.add("Green");
        colors.add("Yellow");
        colors.add("Red");

        System.out.println("HashSet elements: " + colors);
    }
}

In this example, even though we tried to add "Red" twice, the HashSet will only store unique elements.

TreeSet

TreeSet is a sorted collection that implements the NavigableSet interface, which extends the SortedSet interface. It uses a Red-Black Tree (a self-balancing binary search tree) for storing elements. The main characteristics of TreeSet are:

  1. It maintains elements in a sorted order (natural order by default or using a custom comparator).
  2. It does not allow null values.
  3. It has O(log(n)) performance for basic operations (add, remove, and contains).

Example of using a TreeSet:

import java.util.Set;
import java.util.TreeSet;

public class Main {
    public static void main(String[] args) {
        Set<String> colors = new TreeSet<>();

        colors.add("Red");
        colors.add("Blue");
        colors.add("Green");
        colors.add("Yellow");
        colors.add("Red");

        System.out.println("TreeSet elements: " + colors);
    }
}

In this example, the TreeSet stores the unique elements in a sorted order.

When to use HashSet or TreeSet?

Choose HashSet when:

  1. You need fast insertion, deletion, and retrieval of elements.
  2. You don't require elements to be sorted.
  3. You want to allow a single null value.

Choose TreeSet when:

  1. You need elements to be sorted.
  2. You require additional operations provided by NavigableSet and SortedSet, like first(), last(), headSet(), tailSet(), etc.
  3. You don't want to allow null values.

In this tutorial, we covered the basics of HashSet and TreeSet in Java, their differences, and when to use each implementation. Both HashSet and TreeSet are useful for storing unique elements, but their use cases differ depending on the performance and ordering requirements.

  1. Java Set Interface and Implementations:

    • The Set interface represents an unordered collection of unique elements. HashSet and TreeSet are implementations.
    Set<String> hashSet = new HashSet<>();
    Set<Integer> treeSet = new TreeSet<>();
    
  2. Adding Elements to HashSet in Java:

    • Adding elements to a HashSet.
    Set<String> names = new HashSet<>();
    names.add("Alice");
    names.add("Bob");
    
  3. Removing Elements from HashSet in Java:

    • Removing elements from a HashSet.
    names.remove("Alice");
    
  4. Java HashSet Example Code:

    • Example demonstrating basic operations with HashSet.
    Set<String> fruits = new HashSet<>();
    fruits.add("Apple");
    fruits.add("Banana");
    
  5. Sorting Elements in TreeSet in Java:

    • Elements in a TreeSet are automatically sorted.
    Set<Integer> numbers = new TreeSet<>();
    numbers.add(5);
    numbers.add(2);
    
  6. Java TreeSet Example Code:

    • Example showcasing basic operations with TreeSet.
    Set<String> colors = new TreeSet<>();
    colors.add("Red");
    colors.add("Blue");
    
  7. HashSet and TreeSet with Custom Objects in Java:

    • Using custom objects in both HashSet and TreeSet.
    Set<Person> personSet = new HashSet<>();
    Set<Person> sortedPersonSet = new TreeSet<>(Comparator.comparing(Person::getLastName));
    
  8. HashSet and TreeSet Iterator in Java:

    • Iterating through elements using iterators.
    Iterator<String> hashSetIterator = names.iterator();
    while (hashSetIterator.hasNext()) {
        System.out.println(hashSetIterator.next());
    }