streams - Creating Optional

When we’re writing our own code that produces Optionals, there are three static methods we can use:

  • empty() : Produces an Optional with nothing inside.
  • of(value) : If we already know that value is not null , use this to wrap it in an Optional.
  • ofNullable(value) : Use this if we don’t know that value is not null . It automatically produces Optional.empty if value is null, and otherwise wraps value inside an Optional
// streams/CreatingOptionals.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

class CreatingOptionals {
  static void test(String testName, Optional<String> opt) {
    System.out.println(" === " + testName + " === ");
    System.out.println(opt.orElse("Null")); // the value, if present, otherwise other(Null)
  }

  public static void main(String[] args) {
    test("empty", Optional.empty()); // A container object which may or may not
    // contain a non-null value. If a value is present, isPresent() will return true 
    // and get() will return the value.
    // final class Optional sine 1.8
    test("of", Optional.of("Howdy"));
    try {
      test("of", Optional.of(null));
    } catch (Exception e) {
      System.out.println(e);
    }
    test("ofNullable", Optional.ofNullable("Hi"));
    test("ofNullable", Optional.ofNullable(null));
  }
}
/* Output:
 === empty ===
Null
 === of ===
Howdy
java.lang.NullPointerException
 === ofNullable ===
Hi
 === ofNullable ===
Null
*/

references:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/CreatingOptionals.java

3. https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#orElse-T-

4. https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#of-T-

5. https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#ofNullable-T-

6. http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Optional.java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值