I was curious about how to use Optional orElse () and orElseGet () properly.

Premise

At the time of writing this article, I don't know much about the grammar of java.util.Optional.

Optional is what

Class added in Java8-java.util.Optional

** A container object that may or may not contain non-null values. ** ** by https://docs.oracle.com/javase/jp/8/docs/api/java/util/Optional.html

I see, I don't know.

resemble

Trial code for the time being

Main.java


import java.util.*;

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

        Optional.of("hoge").orElseGet(() -> {
            System.out.println("It's not executed or ElseGet");
            return "";
        });

        Optional.empty().orElseGet(() -> {
            System.out.println("It's orElseGet to be executed");
            return "";
        });

        String piyo = (String)Optional.of("hoge").orElse("It's not returned or Else");
        System.out.println("piyo: " + piyo);

        String piyo2 = (String)Optional.empty().orElse("It's returned or Else");
        System.out.println("piyo2: " + piyo2);

    }
}

result

It's orElseGet to be executed piyo: hoge piyo2: It's returned or Else

In other words ...?

orElse () is executed regardless of whether the contents of Optional are null, and oeElseGet () is executed only when null.

Conclusion

--OrElse () is good because it is useless to write a lambda expression just to return a constant like "returns an empty string or zero if null" --OrElseGet () in the case of "If it is null, do some processing and return the result"

Recommended Posts

I was curious about how to use Optional orElse () and orElseGet () properly.
I thought about how to use Swift's willSet did Set properly.
About the matter that I was addicted to how to use hashmap
How to use java Optional
[Java] How to use Optional ②
[Java] How to use Optional ①
I was curious about all_month and read ActiveSupport DateAndTime :: Calculations
How to use EventBus3 and ThreadMode
How to use equality and equality (how to use equals)
I was curious about how gRPC-Java works, so I tried code reading
I tested how to use Ruby's test / unit and rock-paper-scissors code.
How to use OrientJS and OrientDB together
How to set up and use kapt
How to use substring and substr methods
[Java] Learn how to use Optional correctly
How to use @Builder and @NoArgsConstructor together
[Java] How to use FileReader class and BufferedReader class
[Ruby] How to use gsub method and sub method
Thinking about how to use Ionic-Native, Hybrid and HTML5 for mobile app production
How to use Segmented Control and points to note
How to use scope and pass processing (Jakarta)
[Java] How to use Calendar class and Date class
[Java] I studied polymorphism, so I will summarize how to use it and its merits.
How to use Maven that I can't hear anymore
[Rails] I don't know how to use the model ...
How to use RealSense with ubuntu 20.04 and ROS Noetic
How to use and apply Java's JFrame / Canvas class
How to use Map
How to use rbenv
How to use letter_opener_web
How to use with_option
How to use fields_for
How to use java.util.logging
How to use map
How to use collection_select
How to use Twitter4J
How to use active_hash! !!
How to use MapStruct
How to use hidden_field_tag
How to use TreeSet
[How to use label]
How to use identity
How to use hashes
How to use JUnit 5
How to use Dozer.mapper
How to use Gradle
How to use org.immutables
How to use java.util.stream.Collector
How to use VisualVM
How to use Map
How to use OpenCV 4 on Android and view camera live view
I tried to make Java Optional and guard clause coexist
How to use Font Awesome icon for ul and li
How to call and use API in Java (Spring Boot)
Think about how to divide MVC into M and V
Procedures for passing RealmObject to Fragment and how to use Parceler
A story about misunderstanding how to use java scanner (memo)
How to use Chain API
[Java] How to use Map
How to use Priority Queuing
[Rails] How to use enum