Java HashSet parallelStream() Method

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

Table of Contents

  1. Introduction
  2. parallelStream Method Syntax
  3. Examples
    • Basic Example
    • Real-World Use Case: Processing Active Usernames in Parallel
  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 parallelStream method is a part of the Stream API introduced in Java 8, which provides a powerful way to process sequences of elements in parallel, making it easier to perform bulk operations more efficiently by utilizing multiple cores of the processor.

parallelStream() Method Syntax

The syntax for the parallelStream method is as follows:

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

Examples

Basic Example

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

Example

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

public class HashSetParallelStreamExample {
    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 parallel stream from the HashSet
        Stream<String> parallelStream = set.parallelStream();

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

Output:

Elements in the HashSet (processed in parallel):
Java
C
Python
JavaScript

Real-World Use Case: Processing Active Usernames in Parallel

In a web application, you might want to process active usernames in parallel to speed up operations like sending notifications.

Example

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

public class ActiveUsersParallelStreamExample {
    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" in parallel
        HashSet<String> filteredUsers = activeUsers.parallelStream()
                .filter(username -> username.startsWith("john"))
                .collect(Collectors.toCollection(HashSet::new));

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

Output:

Filtered usernames starting with 'john' (processed in parallel): [john_doe, john_smith]

Example: Summing Elements in a HashSet of Integers in Parallel

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

Example

import java.util.HashSet;

public class HashSetParallelSumExample {
    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 parallel stream
        int sum = numbers.parallelStream().mapToInt(Integer::intValue).sum();

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

Output:

Sum of elements in the HashSet (processed in parallel): 100

Example: Converting a HashSet to an Array using Parallel Streams

You can use the parallelStream method to convert a HashSet to an array in parallel.

Example

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

public class HashSetToArrayParallelExample {
    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 parallel stream
        String[] array = set.parallelStream().toArray(String[]::new);

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

Output:

Array (processed in parallel): [Java, C, Python, JavaScript]

Conclusion

The HashSet.parallelStream() method in Java provides a way to create a parallel Stream with the elements of the HashSet as its source. This method is useful for performing bulk operations on the elements in parallel, making use of multiple processor cores to improve performance. 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 summing numeric elements and converting a HashSet to an array in parallel.

Comments