OptionalInt vs Optional<Integer>

早过忘川 提交于 2019-12-03 00:59:38

Java 8 introduced a whole lot dedicated to primitives. The reason is most likely that boxing primitives can create a lot of waste "boxes".

For example this

OptionalInt optionalFirst = IntStream
    .range(0, 100)
    .filter(i -> i % 23 > 7)
    .findFirst();

Here, an Optional<Integer> as result would be inconsistent. Also methods like ifPresent(IntConsumer consumer) then allow to stay withing the IntStream world. Optional<Integer> would force you to convert (which you can do easily if you want)

There is no need for special support for char or short or byte because all of them can be represented as int. The missing one is boolean but there is not much you can do in a stream with them since there are only 2 values.

There needs to be an OptionalInt class for Java 8's streams to be consistent. If you take a look at the Stream class, you'll see that many of the methods return Optional<T>. However, dealing with a Stream<Integer>, Stream<Long> or any other streams of primitives is exhausting, so there is an IntStream class and a LongStream class which replace the object with its unboxed value. For instance, finding the sum of the elements of a Stream<Integer> is not trivial, whereas for an IntStream, you just call IntStream#sum

In these classes, the JDK helpfully replaces Optional<T> with OptionalInt, OptionalLong, and so forth.

OptionalInt is a container holding value of primitive type int. Primitive types cannot be used as type parameters for generic classes, so there is no way it could be a subclass of Optional<T>.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!