Optionals in Streams for Java

optionals in streams
Difficulty

Optionals are the Java’s way to make sure something comes out of streams, even in those cases where there may not be a result.
The reason for their existence, their “raison d’ĂȘtre” is that, when a return value is defined in a method, that method must necessarily return something.

Use Optionals in Streams

In particular, this can happen for some methods that work with streams and that in some particular cases could simply not return anything but, as just said, this cannot happen in the Java context.
The following methods will return Optional<T> as a result, where T is a Generic type (if you don’t know what Generic types are you will find more at the following link):

  • findAny() [ finds any element in the stream, used for performance instead of findFirst() ]
  • findFirst() [ finds the first element in the stream, even in a parallel context ]
  • max(Comparator<? super T> comparator) [ finds the largest value ]
  • min(Comparator<? super T> comparator) [ finds the major element, optionally based on a comparator ]
  • reduce(BinaryOperator<T> accumulator)[ reduces the elements of a list to a single element ]

And we have similar methods for streams of primitives.

Stream<Double> doubleStream = Stream.of(1.0, 2.0, 3.0);
Optional<Double> aNum = doubleStream.findAny();
if (aNum.isPresent()) {
  Double aDouble = aNum.get();
  // ...
}

Types of Optionals

There are optionals in Java for objects (Optional<T>) and three primitive optionals (OptionalDouble, OptionalLong, OptionalInt).

Pay attenction about OptionalDouble will NOT work here because we are on a stream of Doubles, not a stream of doubles. On object optionals we use get() method and its variations.

  • Optional<T> with its method get()
  • OptionalDouble with its method getAsDouble()
  • OptionalInt with its method getAsInt()
  • OptionalLong with its method getAsLong()

We can also check with ifPresent() method that takes a Consumer.

aNum.ifPresent( n -> System.out.println(n) );

We can create our optional:

Optional<Dog> optDog = Optional.of(aDog);
optDog.ifPresent(System.out::println);

If you have a null object, when you try an ifPresent() on it you’ll have a NullPointerException.

aDog = null;
Optional<Dog> optionalDog = Optional.of(aDog);
optionalDog.ifPresent(System.out::println); // NullPointerException!

In this case we can use the ofNullable() method, that create an empty optional if the object is null.
We can also create empty Optional directly:

Optional<Dog> optDog = Optional.empty();

This not returns NullPointerException.
Or we can handle it with orElse() method, on an Optional and, if is empty, it returns the second:

emptyOptDog.orElse(new Dog());

Optionals are mainly used within streams and are rarely used outside this context.

0
Be the first one to like this.
Please wait...

Leave a Reply

Thanks for choosing to leave a comment.
Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published.
Please do NOT use keywords in the name field. Let's have a personal and meaningful conversation.