Idiomatic way of mapping across Optional with void method

Ken :

I have a Optional and want to call a function with its' contents if present, and throw if not. The problem is map will not take a void method.

    File file;
    //...
    Optional maybeFile  = Optional.ofNullable(file);
    //..
    maybeFile
        .map(f -> writeTo(f, "stuff")) //Compile error: writeTo() is void
        .orElseThrow(() -> new IllegalStateException("File not set"));

How should I implement this while keeping writeTo void?

user7 :

orElseThrow returns the File object if present and so you can write it as

writeTo(maybeFile.orElseThrow(() -> new IllegalStateException("File not set")), "stuff");

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=112605&siteId=1