An Example Method of Java Optionalless thanFoogreater than Converting to Listless thanBargreater than

  • 2021-09-20 20:36:29
  • OfStack

1. Conversion method code


public List<Bar> get(Optional<Foo> foo) {
     return foo.map(x -> x.getBazList()
                          .stream()
                          .map(Baz::getBar)
                          .collect(Collectors.toList()))
               .orElse(Collections.emptyList());
}

Or


public List<Bar> get(Optional<Foo> foo) {
         return foo.map(Foo::getBazList)
                   .stream()
                   .flatMap(Collection::stream)
                   .map(Baz::getBar)
                   .collect(Collectors.toList());
}

2. Optional class method

1) empty ()

Returns an empty Optional instance.

2) equals (Object obj)

Determines whether other objects are equal to Optional.

3) filter (function)

If the value exists and the value returns true via the method, an Optional is returned to describe the value, otherwise an empty Optional is returned.

4) flatMap (function)

If the value exists, the function-processed Optional class is returned; otherwise, an empty Optional is returned

5) get ()

If this value is included in this Optional, a value is returned, otherwise an exception is thrown: NoSuchElementException

6) hashCode ()

Returns the hash code where the value exists, or 0 if the value does not exist.

7) ifPresent (function)

If the value exists, call consumer with the value, otherwise do nothing.

8) isPresent ()

If the value exists, the method returns true, otherwise it returns false.

9) map (function)

If there is a value, the call mapping function is performed on it to get the return value. If the return value is not null, an Optional containing the mapped return value is created as the map method return value, otherwise an empty Optional is returned.

10) static of (value)

Returns 1 Optional that specifies a non-null value.

11) static ofNullable (value)

If it is not null, the specified value described by Optional is returned; otherwise, an empty Optional is returned.

12) orElse (other)

Returns a value if it exists, or other if not.

13) orElseGet (function)

Returns a value if it exists, otherwise triggers the method and returns the result of the method call.

14) orElseThrow (function)

Returns the included value if the value exists, otherwise throws the exception specified by the method

15) toString ()

Returns a non-empty string of 1 Optional

That's Java Optional < Foo > Convert to List < Bar > More on Java Optional < Foo > Convert to List < Bar > Please pay attention to other related articles on this site for code information!


Related articles: