“This is the fifth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Optional

Why use Optional?

Empty objects should not be used to determine system behavior; they are Exceptional values and should be treated as errors, not business logic states

Null can be handled with Optional.

Create the Optional

“Empty “Optional object

  • Of (T value) Creates an Optional object

  • OfNullable (T value) Returns “empty “Optional if null is passed in, otherwise returns the Optional object wrapped with value

    • Wrap null values and “empty “Optional objects: If Optional wraps null, using GET also generates NPE, but if empty() is used to create” empty “Optional objects.
  • Empty () returns the “empty “Optional object

Commonly used method

  • IsPresent () checks whether the Optional wrapper is null: null →false

    • boolean present1 = Optional.ofNullable(new ListNode()).isPresent();
  • Get () gets the value of the Oprional wrapper. If the value is null, an NPE is generated

  • Return value if orElse(T value) is null, otherwise return Optional wrapped value

  • Map () performs the specified transformation method, which is similar to the map() method of stream

  • Filter () checks and filters values securely

  • OrElse () is the deferred invocation version of orElse and can be used when the default specifies that the object returned is a laborious operation

  • OrElseThrow () can raise an exception

Use map() to get elements

Since using GET can cause NPE, use map, see the source code below, if empty, will be automatically converted to empty Optional

Using the orElse() endpoint method, the output value is specified when the output is null

ListNode listNode2 = Optional.ofNullable(listNode).map(e -> e).orElse(new ListNode(2));
Copy the code

test

Null-fetching can be performed using map multi-level nesting

ListNode listNode1 = new ListNode(1); ListNode listNode2 = new ListNode(2); ListNode listNode3 = new ListNode(3); listNode1.next = listNode2; listNode2.next = listNode3; / / 3 layer nested, just can get listNode3 Integer to Integer = Optional. OfNullable (listNode1). The map (e - > e.n ext). The map (e - > e.n ext). The map (e - > e.val).orElse(-1); // The result is 3 system.out.println (integer); / / when the list by the end of the listNode2, set off orElse Integer to Integer = Optional. OfNullable (listNode1). The map (e - > e.n ext). The map (e - > e.n ext). The map (e - >  e.val).orElse(-1); // The result is -1 system.out.println (integer); Integer Integer = Optional. OfNullable (listNode1). Map (e -> {system.out.println (e.val); e = Optional.ofNullable(e.next).orElse(listNode3); return e; }).map(e -> e.next).map(e -> e.val).orElse(-1);Copy the code