在可选的Java 8上执行void操作

在可选的Java 8上执行void操作,java,java-8,functional-programming,optional,Java,Java 8,Functional Programming,Optional,我有一些处理逻辑: public void handle(String uniqueId) { Optional<Config> config = configDAO.find(uniqueId); if (!config.isPresent()) { LOGGER.warn("config not found for uniqueId '{}'", uniqueId); } else { internalHandle(conf

我有一些处理逻辑:

public void handle(String uniqueId) {
    Optional<Config> config = configDAO.find(uniqueId);
    if (!config.isPresent()) {
        LOGGER.warn("config not found for uniqueId '{}'", uniqueId);
    } else {
        internalHandle(config.get());
    }
}
公共无效句柄(字符串唯一ID){
可选配置=configDAO.find(uniqueId);
如果(!config.isPresent()){
warn(“未找到uniqueId{}”的配置,uniqueId);
}否则{
internalHandle(config.get());
}
}
换句话说,我想基于可选值的存在运行两个void操作中的一个

我非常担心在我的代码中不使用
isPresent
,但看起来java8没有提供任何我可以替换此代码的内容。

正如java9中提到的,您可以使用:

使用
if-else
语句实现
ifpresentorese
if非常简单。源代码:

public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction) {
    if (value != null) {
        action.accept(value);
    } else {
        emptyAction.run();
    }
}

public void ifpresentorese(消费者为什么你不想使用它?你是对的,
isPresent
是低级的,而且通常有更好的选择。你能使用Java 9吗?它有
ifpresentorese
,非常适合你的需要。这就是为什么我把这个问题标记为
Java-8
@DenisKurochkin检查这可能有用:没有任何东西可以使用。)在您的代码中,这是java 8的预期方式这就是为什么我将问题标记为
java-8
@DenisKurochkin好吧,这在java 8中显然是不可能的,否则他们就不会在java 9中添加方法……虽然这个答案对目前正在使用java 8的提问者没有帮助,但肯定会帮助其他读者。
public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction) {
    if (value != null) {
        action.accept(value);
    } else {
        emptyAction.run();
    }
}