Google Guava Optional Example

This blog post gives an example for Google Guava Optional, a much better alternative for plain and ugly null checks.

Other Google Guava examples:
Convert List to Map
Iterables Find Example
Iterables Any Example
Convert Map to String


package com.idodevjobs;

import com.google.common.base.Optional;

import java.util.List;

public class GoogleGuavaOptionalExample {
    public static void main(String[] args) {

        // GOOD

        Optional<List<String>> fromNull = Optional.fromNullable(getList());
        if (fromNull.isPresent()) {
            // do something
            System.out.println("not null");
        } else {
            System.out.println("null");
        }

        // BAD

        if (getList() != null) {
            // do something
        }
    }

    private static List<String> getList() {
        return null;
    }
}

This example shows how google guava lambda optional can be used. In your application if there are API calls which can return null, instead of doing typical null checks, Optional can be used for better readability.

Advertisements
This entry was posted in java and tagged , , . Bookmark the permalink.

4 Responses to Google Guava Optional Example

  1. Pingback: Convert List to Map using Google Guava in Java | iDoDevJobs

  2. Pingback: Google Guava Iterables Find Example | iDoDevJobs

  3. Pingback: Google Guava Iterables Any Example | iDoDevJobs

  4. Pingback: Convert Map to String using Google Guava in Java | iDoDevJobs

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s