Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why have multiple version of Optional in Java 8

I noticed that, There are multiple versions of many Types in Java 8.

For example, The introduced Optional class has many flavors of OptionalInt, OptionalLong etc..

Although the Optional has a type Parameter (Optional<T>), we still need some specific types for primitives, Why?

I cannot find a BIG difference between the following:

Optional<Integer> o = Arrays.asList(1, 3, 6, 5).stream().filter(i -> i % 2 == 0).findAny();
System.out.println(o.orElse(-1));

OptionalInt oi = Arrays.stream(new int[] { 1, 3, 6, 5 }).filter(i -> i % 2 == 0).findAny();
System.out.println(oi.orElse(-1));
like image 940
Muhammad Hewedy Avatar asked Apr 27 '14 11:04

Muhammad Hewedy


People also ask

What is the significance of Optional in Java 8?

Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values. It is introduced in Java 8 and is similar to what Optional is in Guava.

When should we use Optional in Java?

Optional is a new type introduced in Java 8. It is used to represent a value that may or may not be present. In other words, an Optional object can either contain a non-null value (in which case it is considered present) or it can contain no value at all (in which case it is considered empty).

Why is Optional required?

The main design goal of Optional is to provide a means for a function returning a value to indicate the absence of a return value. See this discussion. This allows the caller to continue a chain of fluent method calls.


1 Answers

It's true that Optional<Integer> behaves quite similar to OptionalInt from a functional point of view. For example, there is no functional difference between the following to methods:

int foo(int value) {
    return OptionalInt.of(value).orElse(4242);
}
int bar(int value) {
    return Optional.of(value).orElse(4242);
}

However, there can be a difference in performance and efficiency--depending on how the optional types are used and on the capabilities of the JIT compiler. The second method is basically identical to the following method:

int baz(int value) {
    return Optional.of(Integer.valueOf(value))
        .orElse(Integer.valueOf(4242))
        .intValue();
}

As you can see, due to auto-boxing for each method call up to two additional Integer objects will be created. Compared to native types, the creation of an object is expensive, and each additional object increases the pressure on the garbage collection.

That doesn't mean, that it will make a difference for most applications. But it can make a difference, and if it's not there, it lowers the acceptance for Java 8 Streams.

like image 89
nosid Avatar answered Sep 19 '22 16:09

nosid