0
0

More than 1 year has passed since last update.

Optional class ifPresent, map method

Last updated at Posted at 2023-01-25

ifPresent() is given Consumer interface
ifPresentOrElse() is given Consumer interface and Runnable interface
map() is given Function interface, and Function#apply method return
map returns Optional
flatMap() is given Function interface, and Function#apply method return Optional
flatMap returns Optional

public class Outer {
    public static void main(String[] args) {
        Optional<String> o = Optional.of("abc");
        o.ifPresent((str) -> { System.out.println("optional value is " + str);});
        o.ifPresentOrElse(str -> { System.out.println("orelse optional value is " + str);},
                          () ->  { System.out.println("orelse optional value is empty");});
        System.out.println("mapping function is "+ o.<Integer>map(str -> str.length()).get());
        System.out.println("flat mapping function is "+ o.<Integer>flatMap(str -> Optional.of(str.length())).get());
        o = Optional.empty();
        o.ifPresent((str) -> { System.out.println("optional value is " + str);});
        o.ifPresentOrElse(str -> { System.out.println("orelse optional value is " + str);},
                          () ->  { System.out.println("orelse optional value is empty");});
    }
}
optional value is abc
orelse optional value is abc
mapping function is 3
flat mapping function is 3
orelse optional value is empty
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0