DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. Functional Programming in Java 8 (Part 2): Optionals

Functional Programming in Java 8 (Part 2): Optionals

Use Optionals when there is a clear need to represent ‘no result’ or where null is likely to cause errors. Otherwise, stick to nulls.

Niklas Wuensche user avatar by
Niklas Wuensche
·
Feb. 08, 17 · Tutorial
Like (66)
Save
Tweet
Share
31.24K Views

Join the DZone community and get the full member experience.

Join For Free

Hello everybody,

After we’ve made our first big steps into functional programming in the last post, we will talk about Optionals in today’s part.

Why do we need Optionals?

Hand on heart, you also think that null is annoying, don’t you? For every argument which can be null, you have to check whether it is null or not.

if(argument == null) {
    throw new NullPointerException();
}

These lines suck! This is a boilerplate that bloats up your code and can be easily forgotten. So how can we fix that?

Introducing Optionals

In Java 8, java.util.Optional<T> was introduced to handle objects which might not exist better. It is a container object that can hold another object. The Generic T is the type of the object you want to contain.

Integer i = 5;
Optional<Integer> optinalI = Optional.of(i);

The Optional class doesn’t have any public constructor. To create an optional, you have to use Optional.of(object) or Optional.ofNullable(object). You use the first one if the object is never, ever null. The second one is used for nullable objects.

How do optionals work?

Options have two states. They either hold an object or they hold null. If they hold an object, optionals are called present, if they hold null, they are called empty. If they are not empty, you can get the object in the optional by using Optional.get(). But be careful, because a get() on an empty optional will cause a NoSuchElementException. You can check if a optional is present by calling the method Optional.isPresent()

Example: Playing with Optionals

public void playingWithOptionals() {
    String s = "Hello World!";
    String nullString = null;

    Optional<String> optionalS1 = Optional.of(s); // Will work
    Optional<String> optionalS2 = Optional.ofNullable(s); // Will work too
    Optional<String> optionalNull1 = Optional.of(nullString); // -> NullPointerException
    Optional<String> optionalNull2 = Optional.ofNullable(nullString); // Will work

    System.out.println(optionalS1.get()); // prints "Hello World!"
    System.out.println(optionalNull2.get()); // -> NoSuchElementException
    if(!optionalNull2.isPresent()) {
        System.out.println("Is empty"); // Will be printed
    }
}

Common problems when using Optionals

1. Working with Optional and null

public void workWithFirstStringInDB() {
    DBConnection dB = new DBConnection();
    Optional<String> first = dB.getFirstString();

    if(first != null) {
        String value = first.get(); 
        //... 
    }
}

This is just the wrong use of an Optional! If you get an Optional (In the example you get one from the DB), you don’t have to look whether the object is null or not! If there’s no string in the DB, it will return Optional.empty(), not null! If you got an empty Optional from the DB, there would also be a NoSuchElementException in this example.

2. Using isPresent() and get()

2.1. Doing something when the value is present

public void workWithFirstStringInDB() {
    DBConnection dB = new DBConnection();
    Optional<String> first = dB.getFirstString();

    if(first.isPresent()) {
        String value = first.get(); 
        //... 
    }
}

As I already said, you should always be 100% sure if an Optional is present before you use Optional.get(). You wouldn’t get a NoSuchElementException anymore in the updated function. But you shouldn’t check a optional with the isPresent() + get() combo! Because if you do it like that, you could have used null in the first place. You would replace first.isPresent() with first != null and you have the same result. But how can we replace this annoying if-block with the help of Optionals?

public void workWithFirstStringInDB() {
    DBConnection dB = new DBConnection();
    Optional<String> first = dB.getFirstString();

    first.ifPresent(value -> /*...*/);
}

The Optional.ifPresent() method is our new best friend to replace the if. It takes a Function, so a Lambda or method reference, and applies it only when the value is present. If you don’t remember how to use method references or Lambdas, you should read the last part of this series again.

2.2. Returning a Modified Version of the Value

public Integer doubleValueOrZero(Optional<Integer> value) {
    if(value.isPresent()) {
       return value.get() * 2;
    }

    return 0;
}

In this method, we want to double the value of an optional, if it is present. Otherwise, we return zero. The given example works, but it isn’t the functional way of solving this problem. To make this a lot nicer, we have two function that are coming to help us. The first one’s Optional.map(Function<T, R> mapper) and the second one’s Optional.orElse(T other). map takes a function, applies it on the value and returns the result of the function, wrapped in an Optional again. If the Optional is empty, it will return an empty Optional again. orElse returns the value of the Optional it is called on. If there is no value, it returns the value you gave orElse(object) as a parameter. With that in mind, we can make this function a one liner.

public Integer doubleValueOrZero(Optional<Integer> value) {
    return value.map(i -> i * 2).orElse(0);
}

When Should you use Nullable Objects and when Optionals

You can find a lot of books, talks and discussions about the question: Should you use null or Optional in some particular case. And both have their right to be used. In the linked talk, you will find a nice rule which you can apply in most of the cases. Use Optionals when “there is a clear need to represent ‘no result’ or where null is likely to cause errors.”.

So you shouldn’t use Optionals like this:

public String defaultIfOptional(String string) {
    return Optional.ofNullable(string).orElse("default");
}

Because a null check is much easier to read.

public String defaultIfOptional(String string) {
    return (string != null) ? string : "default";
}

You should use Optionals just as a return value from a function. It’s not a good idea to create new ones to make a cool method chain like in the example above. Most of the times, null is enough.

Conclusion

That’s it for today! We have played with the Optional class. It’s a container class for other classes which is either present or not present(empty). We have removed some common code smell that comes with Optionals and used functions as objects again. We also discussed when you should use null and when Optionals.

In the next part, we will use Streams as a new way to handle a Collection of Objects, like Iterables and Collections.

Thanks for reading and have a nice day,

Niklas

Functional programming Object (computer science) Java (programming language)

Published at DZone with permission of Niklas Wuensche, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How to Create a Real-Time Scalable Streaming App Using Apache NiFi, Apache Pulsar, and Apache Flink SQL
  • Kubernetes vs Docker: Differences Explained
  • How Observability Is Redefining Developer Roles
  • 7 Awesome Libraries for Java Unit and Integration Testing

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: