Skip to content

Instantly share code, notes, and snippets.

@izhangzhihao
Created May 25, 2018 07:17
Show Gist options
  • Save izhangzhihao/95d7fc96c942375cfe5372caf967c3d1 to your computer and use it in GitHub Desktop.
Save izhangzhihao/95d7fc96c942375cfe5372caf967c3d1 to your computer and use it in GitHub Desktop.
Optional of throwable
import java.util.Optional;
import java.util.function.Function;
public class Option {
public static <T, V> Optional<V> ofThrowable(T it, Function<T, V> func) {
try {
return Optional.ofNullable(func.apply(it));
} catch (Exception e) {
return Optional.empty();
}
}
}
@mobeigi
Copy link

mobeigi commented Oct 21, 2019

Pretty useful! 👍

@milhouse228
Copy link

nice!

@brunorsch
Copy link

brunorsch commented Mar 18, 2021

Another option:

@FunctionalInterface
public interface ThrowableSupplier<T> {
    T get() throws Exception;
}
public static <T> Optional<T> ofThrowable(final ThrowableSupplier<T> supplier) {
    try {
        return ofNullable(supplier.get());
    } catch (final Exception ignored) {
        return empty();
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment