Java Optional class

Introduction

Java Optional class is designed to work with Lambda and Stream.

Full source

// Demonstrate Optional<T>.

import java.util.Optional;

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

    Optional<String> noVal = Optional.empty();

    Optional<String> hasVal = Optional.of("demo2s.com");

    if (noVal.isPresent())
      System.out.println("This won't be displayed");
    else/*from   w  w  w .j av a 2s  .c  om*/
      System.out.println("noVal has no value");

    if (hasVal.isPresent())
      System.out.println("The string in hasVal is: " + hasVal.get());

    String defStr = noVal.orElse("Default String");
    System.out.println(defStr);
  }
}
import java.util.Optional;

public class Main {
  public static void main(String[] args) {
    Optional<Integer> o = Optional.ofNullable(2);
    Optional<Integer>  o1 = Optional.ofNullable(null);
    int r = sum(o, o1);
    System.out.println(r);/*  www . jav a  2s. c  o m*/
  }

  public static int sum(Optional<Integer> a, Optional<Integer> b) {
    Integer val1 = null;
    Integer val2 = null;
    val1 = a.orElse(new Integer(0));
    val2 = b.orElse(new Integer(0));

    return val1 + val2;
  }
}



PreviousNext

Related