Java Stream How to - Get if present from Optional








Question

We would like to know how to get if present from Optional.

Answer

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
//from w w w  .ja va 2s.c  o m
public class Main {

  public static void main(String[] args) {
    List<String> names = Arrays.asList("XML", "HTML", "Java", "Javascript", "CSS", "Static");

    Optional<String> firstZ = names.stream().filter(name -> name.startsWith("Z")).findFirst();
    if (firstZ.isPresent()) {
        System.out.println(firstZ.get());
    } else {
        System.out.println("No Z's found");
    }
  }
}

The code above generates the following result.