Java Collectors toSet() Method

The toSet() method in Java, part of the java.util.stream.Collectors class, is used to collect elements of a stream into a Set. This method is useful when you need to gather the elements of a stream into a set to ensure uniqueness.

Table of Contents

  1. Introduction
  2. toSet() Method Syntax
  3. Understanding toSet()
  4. Examples
    • Basic Usage
    • Using toSet() with Custom Objects
  5. Real-World Use Case
  6. Conclusion

Introduction

The toSet() method returns a Collector that accumulates the input elements into a new Set. This method is particularly useful for converting streams of data into sets, ensuring that the collected elements are unique.

toSet() Method Syntax

The syntax for the toSet() method is as follows:

public static <T> Collector<T, ?, Set<T>> toSet()

Parameters:

  • This method does not take any parameters.

Returns:

  • A Collector that collects the input elements into a Set.

Throws:

  • This method does not throw any exceptions.

Understanding toSet()

The toSet() method allows you to collect the elements of a stream into a Set. The resulting set is typically a HashSet, which ensures that the elements are unique and provides average constant-time performance for basic operations.

Examples

Basic Usage

To demonstrate the basic usage of toSet(), we will create a stream of integers and collect them into a set.

Example

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class ToSetExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 1, 2);

        // Collect the numbers into a set
        Set<Integer> numberSet = numbers.stream()
                                        .collect(Collectors.toSet());

        System.out.println("Number Set: " + numberSet);
    }
}

Output:

Number Set: [1, 2, 3, 4, 5]

Using toSet() with Custom Objects

This example shows how to use toSet() with a stream of custom objects to collect them into a set.

Example

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class ToSetCustomObjectExample {
    static class Product {
        String name;
        double price;

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

        @Override
        public String toString() {
            return name + " ($" + price + ")";
        }

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

            Product product = (Product) o;

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

        @Override
        public int hashCode() {
            int result;
            long temp;
            result = name.hashCode();
            temp = Double.doubleToLongBits(price);
            result = 31 * result + (int) (temp ^ (temp >>> 32));
            return result;
        }
    }

    public static void main(String[] args) {
        List<Product> products = Arrays.asList(
            new Product("Product A", 10.0),
            new Product("Product B", 20.5),
            new Product("Product C", 15.8),
            new Product("Product A", 10.0)
        );

        // Collect the products into a set
        Set<Product> productSet = products.stream()
                                          .collect(Collectors.toSet());

        System.out.println("Product Set: " + productSet);
    }
}

Output:

Product Set: [Product A ($10.0), Product C ($15.8), Product B ($20.5)]

Real-World Use Case

Collecting Unique Employee Names

In real-world applications, the toSet() method can be used to collect the unique names of employees into a set.

Example

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class EmployeeNameSetExample {
    static class Employee {
        String name;
        int age;

        Employee(String name, int age) {
            this.name = name;
            this.age = age;
        }

        String getName() {
            return name;
        }
    }

    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
            new Employee("Alice", 30),
            new Employee("Bob", 25),
            new Employee("Charlie", 35),
            new Employee("Alice", 28)
        );

        // Collect the unique employee names into a set
        Set<String> nameSet = employees.stream()
                                       .map(Employee::getName)
                                       .collect(Collectors.toSet());

        System.out.println("Name Set: " + nameSet);
    }
}

Output:

Name Set: [Bob, Alice, Charlie]

Conclusion

The Collectors.toSet() method is used to collect the elements of a stream into a Set. This method is particularly useful for converting streams of data into sets, ensuring that the collected elements are unique. By understanding and using this method, you can efficiently manage collection operations in your Java applications.

Comments