Get startedGet started for free

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.

This exercise is part of the course

Optimizing Code in Java

View Course

Exercise instructions

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

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

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;
        }
    }
}
Edit and Run Code