Java HashSet stream() Method

The HashSet.stream() method in Java is used to create a sequential Stream with the elements of the HashSet as its source.

Table of Contents

  1. Introduction
  2. stream Method Syntax
  3. Examples
    • Basic Example
    • Real-World Use Case: Filtering Active Usernames
  4. Conclusion

Introduction

The HashSet class in Java is part of the Java Collections Framework and implements the Set interface. A HashSet is used to store unique elements. The stream method is a part of the Stream API introduced in Java 8, which provides a powerful way to process sequences of elements, making it easier to perform bulk operations, such as filtering, mapping, and reducing.

stream() Method Syntax

The syntax for the stream method is as follows:

public Stream<E> stream()
  • The method does not take any parameters.
  • The method returns a sequential Stream with the elements of the HashSet as its source.

Examples

Basic Example

In this example, we'll use the stream method to create a stream from a HashSet and perform a simple operation on the elements.

Example

import java.util.HashSet;
import java.util.stream.Stream;

public class HashSetStreamExample {
    public static void main(String[] args) {
        // Creating a HashSet of Strings
        HashSet<String> set = new HashSet<>();
        set.add("Java");
        set.add("Python");
        set.add("C");
        set.add("JavaScript");

        // Creating a stream from the HashSet
        Stream<String> stream = set.stream();

        // Printing each element in the HashSet using the stream
        System.out.println("Elements in the HashSet:");
        stream.forEach(System.out::println);
    }
}

Output:

Elements in the HashSet:
Java
C
Python
JavaScript

Real-World Use Case: Filtering Active Usernames

In a web application, you might want to filter active usernames that match a certain criterion using a stream.

Example

import java.util.HashSet;
import java.util.stream.Collectors;

public class ActiveUsersStreamExample {
    public static void main(String[] args) {
        // Creating a HashSet to store active usernames
        HashSet<String> activeUsers = new HashSet<>();
        activeUsers.add("john_doe");
        activeUsers.add("jane_smith");
        activeUsers.add("alice_jones");
        activeUsers.add("john_smith");

        // Filtering usernames that start with "john"
        HashSet<String> filteredUsers = activeUsers.stream()
                .filter(username -> username.startsWith("john"))
                .collect(Collectors.toCollection(HashSet::new));

        // Printing the filtered usernames
        System.out.println("Filtered usernames starting with 'john': " + filteredUsers);
    }
}

Output:

Filtered usernames starting with 'john': [john_doe, john_smith]

Example: Converting a HashSet to an Array using Streams

You can use the stream method to convert a HashSet to an array.

Example

import java.util.HashSet;
import java.util.stream.Stream;

public class HashSetToArrayExample {
    public static void main(String[] args) {
        // Creating a HashSet of Strings
        HashSet<String> set = new HashSet<>();
        set.add("Java");
        set.add("Python");
        set.add("C");
        set.add("JavaScript");

        // Converting the HashSet to an array using the stream
        String[] array = set.stream().toArray(String[]::new);

        // Printing the array
        System.out.println("Array: " + java.util.Arrays.toString(array));
    }
}

Output:

Array: [Java, C, Python, JavaScript]

Example: Summing Elements in a HashSet of Integers

You can use the stream method to perform operations on numeric data, such as summing the elements.

Example

import java.util.HashSet;

public class HashSetSumExample {
    public static void main(String[] args) {
        // Creating a HashSet of Integers
        HashSet<Integer> numbers = new HashSet<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(40);

        // Summing the elements in the HashSet using the stream
        int sum = numbers.stream().mapToInt(Integer::intValue).sum();

        // Printing the sum
        System.out.println("Sum of elements in the HashSet: " + sum);
    }
}

Output:

Sum of elements in the HashSet: 100

Conclusion

The HashSet.stream() method in Java provides a way to create a sequential Stream with the elements of the HashSet as its source. This method is useful for performing bulk operations on the elements, such as filtering, mapping, and reducing. By understanding how to use this method, you can efficiently manage and process elements in your Java applications. The examples provided demonstrate basic usage, real-world scenarios, and advanced features like converting a HashSet to an array and summing numeric elements.

Comments