我需要使用Java 8 Optional方法获取包装值,或者调用void返回Consumer lambda [英] I need to use a Java 8 Optional method that either gets the wrapped value, or calls a void return Consumer lambda

查看:125
本文介绍了我需要使用Java 8 Optional方法获取包装值,或者调用void返回Consumer lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不熟悉在Java 8中使用选项。我知道方法orElseGet()需要一个供应商,orElseThrow()也需要一个抛出异常的供应商。 orElseThrow()可能是一个很好用的,如果我可以构造我自己的异常并在触发该异常时执行某些操作。



我的主要目标是使用一种方法将获得未包装的值,或者如果可选的包装为null,则实际执行完全不同的函数。



寻找最接近的东西:

  class DoInsteadClass {
public void doInstead(){
//请改为
}
}


可选< String> myString =你好;
num.orElse(DoInsteadClass :: doInstead);

如果执行此操作的唯一方法是orElseThrow(),并且只要我能处理异常用'做这个代替'代码,也应该没问题。它只是使我的代码库更大,因为我必须为2或3个案例创建一些不同的自定义实用程序供应商,其中我的一些可选值将返回null。



问题is,.ifPresent()使用值调用指定的使用者,否则不执行任何操作。如果值为null,我需要它来进行SOMETHING。我当前的代码使用自定义的解决方法,我首先检查值是否为null,如果是,则执行所选的函数。然后下一个语句是检查ifPresent()的语句。所以这是做同样的事情,我只是在寻找一个更加糖涂层的一个声明版本。

解决方案

在JDK中9将会有一个 ifPresentOrElse 方法将允许它。

但是,暂时你可以选择对于if语句,使用 if(num.isPresent()),或编写自己的可重用 ifPresentOrElse 方法。 / p>

I am new to using optionals in Java 8. I know the method orElseGet() takes a supplier and orElseThrow() also takes a supplier that throws an exception. orElseThrow() might be a good one to use if I can construct my own exception and do something when that exception is triggered.

My main goal is to use a method that will either get the unwrapped value, or if the optional wraps null, then to actually execute an entirely different function.

Looking for the closest thing to:

class DoInsteadClass {
     public void doInstead() {
          // Do this instead
     }
}


Optional<String> myString = "Hello";
num.orElse(DoInsteadClass::doInstead);

If the only way to do this is orElseThrow(), and as long as I can handle the exception with the 'do this instead' code, that should be fine too. It just makes my codebase larger because I have to create a few different custom utility suppliers for the 2 or 3 cases where some of my optional values would return null.

The problem is, .ifPresent() invokes the specified consumer with the value, otherwise does nothing. I need it to DO SOMETHING if the value is null. My current code utilizes a custom workaround where I first check if the value is null, and if it is, execute a chosen function. Then the next statement is the one that checks for ifPresent(). So this is doing the same thing, I am just looking for a more sugar-coated, one statement version.

解决方案

In JDK 9 there will be an ifPresentOrElse method that will allow it.
For the time being, however, you may opt for the if statement, with if(num.isPresent()), or write your own reusable ifPresentOrElse method.

这篇关于我需要使用Java 8 Optional方法获取包装值,或者调用void返回Consumer lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆