Stream API parallel processing

>Parallel processingis a feature of the Stream API in Java that allows stream operations to be executed concurrently on multiple threads. It can significantly improve the performance of certain operations by leveraging the power of multi-core processors.

Example 1: Sum of numbers

Suppose we have a list of integers and we want to calculate the sum of those numbers using parallel processing.

List numbers = List.of(1, 2, 3, 4, 5);
int sum = numbers.parallelStream()
                 .mapToInt(Integer::intValue)
                 .sum();

output: Sum: 15				 

Example 2: Filter even numbers Let's say we have a list of integers and we want to filter out the even numbers using parallel processing.

		List numbers = List.of(1, 2, 3, 4, 5);

		List evenNumbers = numbers.parallelStream()
                                   .filter(n -> n % 2 == 0)
                                   .collect(Collectors.toList());
output: Even numbers: [2, 4]

Example 3: Find maximum value Suppose we have a list of integers and we want to find the maximum value using parallel processing.


List numbers = List.of(1, 7, 3, 9, 5);

int max = numbers.parallelStream()
                 .max(Integer::compare)
                 .orElse(0);
output: Maximum value: 9

Example 4: String concatenation Let's say we have a list of strings and we want to concatenate them using parallel processing.


List strings = List.of("Hello", "World", "Java");

String result = strings.parallelStream()
                       .reduce("", (a, b) -> a + " " + b);

output: Concatenated string: Hello World Java

In all these examples, the parallelStream() method is used to convert the stream into a parallel stream, enabling parallel processing. The operations like map, filter, reduce, and others are executed concurrently on multiple threads, improving the overall performance of the computation. Note: While parallel processing can enhance performance in certain scenarios, it may not always be beneficial or suitable for all types of operations. It's important to consider the nature of the operation, the size of the data set, and other factors before deciding to use parallel processing.

Post a Comment

Previous Post Next Post