本文介绍了我可以不映射/ flatMap一个OptionalInt吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么似乎没有 map() / flatMap() OptionalInt或其他原始的可选方法味道?

Why does there seem to be no map()/flatMap() methods on OptionalInt or other primitive optional flavors?

stream()地图操作允许在对象和基元之间进行转换。但是为什么Optional不利用这个?

The stream() map operations allow conversion between objects and primitives. But why does Optional not exploit this?

OptionalInt profileId = OptionalInt.of(124);

Optional<Profile> profile = profileId.map(i -> getProfile(i));  //no such valid map() method!


推荐答案

原始期权没有地图 flatMap 过滤器方法设计。

Primitive optionals haven't map, flatMap and filter methods by design.

此外,根据你不应该使用它们。
在流上使用原语的理由是性能原因。在大量元素的情况下,装箱/拆箱开销很重要。但这是毫无意义的,因为在Optional中只有一个元素。

Moreover, according to Java8 in Action p.305 you shouldn't use them.The justification of use primitive on streams are the performance reasons. In case of huge number of elements, boxing/unboxing overhead is significant. But this is senselessly since there is only one element in Optional.

此外,请考虑示例:

public class Foo {
    public Optional<Integer> someMethod() {
        return Optional.of(42);
    }
}

用作方法参考:

.stream()
.map(Foo::someMethod)

如果您将someMethod的返回类型更改为 OptionalInt

If you change return type of someMethod to OptionalInt:

public OptionalInt someMethod() {
    return OptionalInt.of(42);
}

您不能将它用作方法参考,代码将无法编译:

You cannot use it as method reference and code will not compile on:

.map(Foo::someMethod)

这篇关于我可以不映射/ flatMap一个OptionalInt吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 22:53