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 Optional’s are .

Read more: How to use optional in java 8 streams
  • 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;
import java.util.stream.Collectors;

/*
* @author javabeginnerstutorial.com
*/
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 = list.stream().map(jbt::getName)
                   .filter(Optional::isPresent)
                   .map(Optional::orElseThrow)
                   .collect(Collectors.<em>joining</em>(","));

System.<em>out</em>.println(name);

// Since JDK 9
 name = list.stream()
            .map(jbt::getName)
            .flatMap(Optional::stream)
            .collect(Collectors.<em>joining</em>(","));

 System.<em>out</em>.println(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 = list.stream()
            .map(jbt::getName)
            .map(name1 -> name1.orElse("NO_NAME"))
            .collect(Collectors.<em>joining</em>(","));

 System.<em>out</em>.println(name);
}
}

class jbt {

private String name;
private Integer age;

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


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

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

Leave 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.