LoslegenKostenlos loslegen

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.

The Image class was preloaded for you.

Diese Übung ist Teil des Kurses

Optimizing Code in Java

Kurs anzeigen

Anleitung zur Übung

  • 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.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

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;
    }
}
Code bearbeiten und ausführen