Here's some code.
public void blur(final int x, final int y, final int w, final int h) {
final Picture p = new Picture(this);
IntStream.range(x, x + w).parallel().forEach(i
-> IntStream.range(Y, Y + h).forEach(j
-> {
final Pixel pixel = this.getPixel(i, j);
final java.util.List<Pixel> others
= Arrays.asList(
p.getPixel(i - 1, j),
p.getPixel(i, j - 1),
p.getPixel(i, j + 1),
p.getPixel(i + 1, j),
p.getPixel(i - 1, j - 1),
p.getPixel(i + 1, j + 1),
p.getPixel(i - 1, j + 1),
p.getPixel(i + 1, j - 1),
pixel
);
pixel.setBlue((int) (others.stream()
.mapToInt(Pixel::getBlue).average().getAsDouble()));
pixel.setRed((int) (others.stream()
.mapToInt(Pixel::getRed).average().getAsDouble()));
pixel.setGreen((int) (others.stream()
.mapToInt(Pixel::getGreen).average().getAsDouble()));
})
);
}
Some languages offer a parallel for-loop for a series of integers. Java doesn't seem to, but I don't feel like multithreading the "correct way" (like fork-join, etc.)
Is this efficient? I have found that this is indeed faster than the standard for (int i ...
code. Which of the loops (streams) should I make parallel? Is this good coding practice?