Junior — Middle
Kuidas Java-s rakendatakse andmete paralleelne töötlemine kasutades meetodit parallelStream?
sobes.tech AI
Vastus AI-lt
In Java, the parallelStream() method allows performing operations on collections in parallel, using multiple threads from a shared ForkJoinPool. This speeds up processing large volumes of data by parallelizing tasks.
Example of usage:
import java.util.Arrays;
import java.util.List;
public class ParallelStreamExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
int sumOfSquares = numbers.parallelStream()
.mapToInt(n -> n * n)
.sum();
System.out.println("Sum of squares: " + sumOfSquares);
}
}
In this example, the calculation of the squares of numbers and their summation is performed in parallel, which can improve performance on multi-core processors. It is important that operations are side-effect free to avoid thread safety issues.