Java 将 Optional 的值分配给变量(如果存在)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39713058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:23:22  来源:igfitidea点击:

Assign value of Optional to a variable if present

javalambdaoptional

提问by chrisrhyno2003

Hi I am using Java Optional. I saw that the Optional has a method ifPresent.

嗨,我正在使用 Java Optional。我看到Optional有一个方法ifPresent。

Instead of doing something like:

而不是做类似的事情:

Optional<MyObject> object = someMethod();
if(object.isPresent()) {
    String myObjectValue = object.get().getValue();
}

I wanted to know how I can use the Optional.ifPresent() to assign the value to a variable.

我想知道如何使用 Optional.ifPresent() 将值分配给变量。

I was trying something like:

我正在尝试类似的事情:

String myValue = object.ifPresent(getValue());

What do I need the lambda function to be to get the value assigned to that variable?

我需要什么 lambda 函数来获取分配给该变量的值?

采纳答案by CompilaMente

You could use #orElseor orElseThrowto improve the readbility of your code.

您可以使用#orElseorElseThrow来提高代码的可读性。

Optional<MyObject> object = someMethod();
String myValue = object.orElse(new MyObject()).getValue();


Optional<MyObject> object = someMethod();
String myValue = object.orElseThrow(RuntimeException::new).getValue();

回答by yshavit

You need to do two things:

你需要做两件事:

  1. Turn your Optional<MyObject>into an Optional<String>, which has a value iff the original Optional had a value. You can do this using map: object.map(MyObject::toString)(or whatever other method/function you want to use).
  2. Get the String value of of your Optional<String>, or else return a default if the Optional doesn't have a value. For that, you can use orElse
  1. 把你的Optional<MyObject>变成 an Optional<String>,如果原来的 Optional 有一个值,它就有一个值。您可以使用map:(object.map(MyObject::toString)或您想使用的任何其他方法/函数)来执行此操作。
  2. 获取 的 String 值,Optional<String>如果 Optional 没有值,则返回默认值。为此,您可以使用orElse

Combining these:

结合这些:

String myValue = object.map(MyObject::toString).orElse(null);

回答by Optional

Quite late but I did following:

很晚了,但我做了以下事情:

String myValue = object.map(x->x.getValue()).orElse("");
                           //or null. Whatever you want to return.

回答by Ankur

Optional l = stream.filter..... // java 8 stream condition

可选 l = stream.filter..... // java 8 流条件

        if(l!=null) {
            ObjectType loc = l.get();
            Map.put(loc, null);
        }

回答by davidddp

.findFirst()returns a Optional<MyType>, but if we add .orElse(null)it returns the get of the optional if isPresent(), that is (MyType), or otherwise a NULL

.findFirst()返回 a Optional<MyType>,但如果我们添加.orElse(null)它,则返回可选 if 的 get isPresent(),即 ( MyType) ,否则返回 aNULL

MyType s = newList.stream().filter(d -> d.num == 0).findFirst().orElse(null);