java 从 Optional<Object> 创建对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42977137/
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-11-03 06:59:29  来源:igfitidea点击:

Creating an Object from Optional<Object>

javajava-streamoptional

提问by Hans

So I've created a stream which comes from a List but I'm having some trouble converting it into a <ObjectType>,here's what I've tried:

所以我创建了一个来自 List 的流,但是我在将它转换为<ObjectType>,这里时遇到了一些问题,这就是我尝试过的:

ObjectType sco = getList().stream()
                          .filter(p -> p.getValue() == value)
                          .findFirst(); //also tried .orElse(null);

would anyone, please, be so kind as to suggest where I'm going wrong? (I apologize if this has been asked before but I couldn't find a discussion on this particular topic (or didn't know the proper terms to search for))

有没有人请好心建议我哪里出错了?(如果之前有人问过这个问题,我深表歉意,但我找不到关于这个特定主题的讨论(或者不知道要搜索的正确术语))

Thanks in advance!

提前致谢!

回答by Brian Agnew

findFirst()gives you an Optionaland you then have to decide what to do if it's not present. So findFirst().orElse(null)should give you the object or null if it's not present

findFirst()给你一个Optional,然后你必须决定如果它不存在该怎么办。所以findFirst().orElse(null)应该给你对象或 null 如果它不存在

You couldjust do a .get()on the Optional, but that could be regarded as poor practice since get()will throw an exception if Optionalhas no content. You should normally assert presence/absence of the Optionaland decide what to do in each case (that's why it's there - so that you know something is truly optionaland you have to determine what to do)

可以只在.get()上做一个Optional,但这可能被认为是不好的做法,因为get()如果Optional没有内容就会抛出异常。您通常应该断言 存在/不存在Optional并决定在每种情况下做什么(这就是它存在的原因 - 这样您就知道某些事情确实是可选的,并且您必须确定要做什么)

If you have an action you want to perform on object presence, and you don't want to do anything on absence, you can call .ifPresent()and provide a lambda as an argument. That will be called with the contained object, if present.

如果您想在对象存在时执行某个操作,并且不想在缺席时执行任何操作,则可以调用.ifPresent()并提供一个 lambda 作为参数。如果存在,将使用包含的对象调用该对象。

回答by Josh

I think you may be looking for findFirst().or Else(null). findFirst()will return an Optional- empty in the case of an empty steam.

我想你可能正在寻找findFirst().or Else(null). 如果蒸汽为空,findFirst()将返回Optional- 空。

Unless I misunderstood your comment. Have you tried this, or did you try orElse(null)without findFirst()?

除非我误解了你的评论。你有没有试过,还是你试试orElse(null)findFirst()