MulaiMulai sekarang secara gratis

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.

Latihan ini adalah bagian dari kursus

Optimizing Code in Java

Lihat Kursus

Petunjuk latihan

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

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

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;
    }
}
Edit dan Jalankan Kode