Optimizing image processing with parallel streams
You're working on an image processing application that applies filters to large batches of images. Currently, the application processes images sequentially, but this is becoming a bottleneck as the number of images increases. You are tasked with implementing a parallel stream solution to improve performance.
Este exercício faz parte do curso
Optimizing Code in Java
Instruções do exercício
- Convert the stream to a parallel stream for faster processing.
- Apply filters to all images in the stream.
- Collect the images to a single list.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
import java.util.*;
import java.util.stream.*;
public class ImageProcessor {
public static void main(String[] args) {
List images = generateImages(500);
List result = images
// Use a parallel stream for multi-thread processing
.___
// Apply filters to each image using `map()`
.___(image -> applyFilters(image))
// Collect images to a single list
.___(Collectors.toList());
}
static Image applyFilters(Image image) {
image = blur(image);
image = sharpen(image);
return image;
}
static Image blur(Image image) {
process(); return new Image(image.id, image.width, image.height);
}
static Image sharpen(Image image) {
process(); return new Image(image.id, image.width, image.height);
}
static void process() {
for (int i = 0; i < 100000; i++) {
double result = Math.sin(i) * Math.cos(i);
}
}
static List generateImages(int count) {
List list = new ArrayList<>();
for (int i = 0; i < count; i++) {
list.add(new Image(i, 1920, 1080));
}
return list;
}
static class Image {
int id, width, height;
Image(int id, int width, int height) {
this.id = id; this.width = width; this.height = height;
}
}
}