Saturday, January 03, 2015

Using Optional Effectively in Java 8

Optional<T> was added in Java 8, and according to its documentation it is defined as "a container object which may or may not contain a non-null value..."

I have recently been spending some time getting familiar with the Stream API, also introduced in Java 8, and a lot of the terminating methods of the Stream API returns an Optional<T>...

At first encounter with Optional<T>, my first thought was asking what real advantage does this offer? How is it different from checking if an object is null before calling its methods?

The Optional<T> has the isPresent() and get() methods which can be used to check if the enclosing object is null or not, and then retrieve it. Like so:

Optional<SomeType> someValue = someMethod();
if (someValue.isPresent()) { // check
    someValue.get().someOtherMethod(); // retrieve and call
}

But exactly the same thing can be done with plain null checks with the code looking almost the same:

SomeType someValue = someMethod();
if (someValue != null) {
    someValue.someOtherMethod();
}

What then is Optional<T> good for?


Thursday, January 01, 2015

First Blogpost of 2015!

...and the first post of 2015 would be...all first posts of all previous new years since I started blogging!

How meta can that get ;)

So here we go, from 2006 till now!