I tried to reorganize the old code to use streams, and my first approach:
public void run() throws IOException { Files.list(this.source) .filter(Images::isImage) .map(Image::new) .filter(image -> image.isProportional(this.height, this.width)) .map(image -> image.resize(this.height, this.width)) .forEach(image -> Images.write(image, this.destination)); }
This is not compilation, as the new Image () and Images.write () call IOExceptions.
Acquiring these exceptions with UncheckedIOException will not lead to a trick, since I do not want to stop processing other images if one of them does not work.
So, I finished writing 2 private methods:
private Optional<Image> createImage(Path imagePath) { try { return Optional.of(new Image(imagePath)); } catch (IOException e) { return Optional.empty(); } } private void write(Image image) { try { Images.write(image, this.destination); } catch (IOException e) {
createImage () returns optional as it seems reasonable. However, after that, my code became really ugly:
public void run() throws IOException { Files.list(source) .filter(Images::isImage) .map(this::createImage) .filter(image -> image.isPresent() && image.get().isProportional(this.height, this.width)) .map(image -> image.get().resize(this.height, this.width)) .forEach(this::write); }
Is there a way to avoid using get () and isPresent () in this code?
Thanks!
java java-8 java-stream optional
gaijinco
source share