Skip to content

Instantly share code, notes, and snippets.

@wordhulhasan
Last active November 20, 2019 09:53
Show Gist options
  • Save wordhulhasan/0180dd837ed3b617484e214218c8a6eb to your computer and use it in GitHub Desktop.
Save wordhulhasan/0180dd837ed3b617484e214218c8a6eb to your computer and use it in GitHub Desktop.
Java Optional Api Examples

Data Set

    private List<Wizards> getWizards(){
        return List.of(
                new Wizards("Gryfindor","phoenix feather core","Half Blood","Male","Harry Potter"),
                new Wizards("Gryfindor","unicorn hair core","Pure Blood","Male","Ronald Wisely"),
                new Wizards("Gryfindor","dragon heart string core","Mud Blood","Female","Hermione Granger"),
                new Wizards("Slytherin","unicorn hair core","Pure Blood","Male","Draco Malfoy"),
                new Wizards("Ravenclaw","unicorn hair core","Pure Blood","Male","Cedric Diggory")

        );
    }

JAVA 8 Methods

  1. Empty Creation
  2. Create with Static Method of
  3. ofNullable
  4. If Present
  5. Or Else
  6. orElseGet
  7. orElseThrow
  8. Get
  9. Map
  10. Filter

JAVA 9 and Onward Methods

  1. ifPresentOrElse
  2. or
  3. Stream
  4. GetOrElseThrow

Empty creation

To create an empty Optional object, we simply need to use its empty static method

    Optional<Wizard> empty = Optional.empty();
    System.out.println(empty.isPresent());

Create With Static Method Of

We can also create an Optional object with the static method of:

    Optional<Wizard> wizard = Optional.of(getWizards().get(0));
    System.out.println(wizard.isPresent());

Create Null With Method OfNullable

in case we expect some null values, we can use the ofNullable() method:

    Optional<Wizard> wizard2 = Optional.ofNullable(null);
    System.out.println(wizard2.isPresent());

ifPresent

The ifPresent() method enables us to run some code on the wrapped value if it's found to be non-null. Before Optional, we'd do:

    empty.ifPresent(name-> System.out.println(empty.get().getName()));
    wizard.ifPresent(name-> System.out.println(wizard.get().getName()));

orElse

The orElse() method is used to retrieve the value wrapped inside an Optional instance. It takes one parameter which acts as a default value. The orElse() method returns the wrapped value if it's present and its argument otherwise:

        wizard1 = Optional.ofNullable(wizard_null)
                .orElse(getWizards().get(1));
        System.out.println(wizard1.getName());

orElseGet

The orElseGet() method is similar to orElse(). However, instead of taking a value to return if the Optional value is not present, it takes a supplier functional interface which is invoked and returns the value of the invocation:

        Wizard wizard_null = null;
        Wizard wizard1 = Optional.ofNullable(wizard_null)
                .orElseGet(() -> {
                    // n number of complicated lines
                    return getWizards().get(2);
                });
        System.out.println(wizard1.getName());

orElseThrow

The orElseThrow() method follows from orElse() and orElseGet() and adds a new approach for handling an absent value. Instead of returning a default value when the wrapped value is not present, it throws an exception:

        wizard1 = Optional.ofNullable(wizard_null)
                .orElseThrow(
                        IllegalAccessError::new
                );

Get

The final approach for retrieving the wrapped value is the get() method:

        wizard.ifPresent(name-> System.out.println(wizard.get().getName()));

Map

transform the Optional value with the map() method:

        Optional<List<Wizard>> listOptional = Optional.of(getWizards());

        Integer listSize = listOptional.map(List::size)
                .orElse(0);

        System.out.println(listSize);

Filter

We can run an inline test on our wrapped value with the filter method. It takes a predicate as an argument and returns an Optional object. If the wrapped value passes testing by the predicate, then the Optional is returned as-is.

        System.out.println(wizard.filter(y-> y.getHouse().equals("Gryfindor")).isPresent());
        System.out.println(listOptional.filter(wizards -> wizard.get().getHouse().equals("Gryfindor")).get());

JAVA 9 and Onwards

ifPresentOrElse

Let's try ifPresentOrElse out by not only providing a publish method, but also an alternative Runnable function that will create a notification saying that the article wasn't published.

wizard.ifPresentOrElse(  
  this::publish,                       
  this::notifyThatNothingWasPublished
);

or

This method is enabling us to provide a supplier with an alternative Optional that will be returned if the original Optional is empty.

        Optional<Wizard> orWizard = getWizard().or(() -> Optional.of(getWizards().get(4)));
        System.out.println(orWizard.get().getName()); 

Stream

What this method does is to convert our Optional into a Stream, meaning that if the Optional contains a value it'll become a Stream of one element. If the Optional is empty, it'll create an empty stream.

        Stream<Wizard> wizardStream = Stream.concat(
                orWizard.stream(), getWizardStream()
        );

GetOrElseThrow

This is a quite similar method to the Optional.orElseThrow(exceptionSupplier), which allows us to define the exception by wrapping it in a Supplier.

getWizard().orElseThrow(IllegalStateException::new); 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment