Scroll to top

How to use optional in java 8 streams

In this article we will learn how to use optional in java 8 streams. Optional is a container object which may or may not contain null value. Some of the most important methods in Optionals are .

  • isPresent : if a value is present returns true else return false.
  • isEmpty: Opposite of isPresent. If a value is not present return true.
  • stream(): Introduced in JDK 9. If a value is present this method returns a sequential Stream containing the value or else returns an empty stream.
  • get: If a value is present return value else throws NoSuchElementException.
  • orElseThrow: This method is introduced in JDK10. Code wise there is no difference between this and above get method. The reasoning behind this method is to use proper naming of the method. More detail about this can be found here. Instead of get, orElseThrow should be used.

So now lets look into the code on how to use optional in Java 8 stream. In this example we will try to see how to filter null values or provide a default value if value is not.

First we will see how to filter null values using java 8 and Java 9 Optional.

package com.jbt.core;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

* @author
public class optional_java_8_stream {

public static void main(String[] args) {

List<jbt> list = new ArrayList<>();
list.add(new jbt("name1", 12));
list.add(new jbt("name2", null));
list.add(new jbt(null, 12));

 String name =


// Since JDK 9
 name =


 //orElse method can be used to provide default value incase there is no value present. Like in this case NO_NAME will be provided when name is null.
 name =
            .map(name1 -> name1.orElse("NO_NAME"))


class jbt {

private String name;
private Integer age;

public jbt(String name, Integer age) { = name;
 this.age = age;

public Optional<String> getName() {
if (name == null) {
  return Optional.empty();
 return Optional.of(name);

public Optional<Integer> getAge() {
if (age == null) {
  return Optional.empty();
 return Optional.of(age);

Author avatar

Post a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.