Aan de slagGa gratis aan de slag

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.

Deze oefening maakt deel uit van de cursus

Optimizing Code in Java

Cursus bekijken

Oefeninstructies

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

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

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 bewerken en uitvoeren