Why do you have several options options in Java 8

I noticed that in Java 8 there are several versions of many types.

For example, the introduced class Optionalhas many varieties OptionalInt, OptionalLongetc.

Although it Optionalis of type Parameter ( Optional<T>), we still need some specific types for primitives, Why?

I cannot find the 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));
+4
source share
1 answer

It is true that it Optional<Integer>behaves very similarly OptionalIntfrom a functional point of view. For example, there is no functional difference between the following methods:

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

- , JIT. :

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

, - Integer. , .

, . , , Java 8.

+8

Source: https://habr.com/ru/post/1538262/


All Articles