Java8 to start now ~ Optional ~

Part 1: Java 8 ~ for Each and Lambda Expression ~ Part 2: Java 8 ~ Stream API ~ to start now The third: Java8 to start now-date and time API-

Optional is a class that handles things that may or may not have non-null values. ʻOptional ` is a type that may or may not have some string

Generate Optional

Has no value

Optional emptyCase = Optional.empty();

Generate an empty Optional

Must have a value

Optional presentCase = Optional.of("example");

Generate Optional with value If you pass null as an argument, you will get a NullPointerException

May or may not have value

Optional nullableNullCase = Optiona.ofNullable(null);
Optional nullableNotNullCase = Optiona.ofNullable("example");

Generates an empty Optional if the argument is null, otherwise creates an Optional with the argument value

Use of Optional

Determine if there is a value

isPresent Returns true if it has a value, false otherwise

Optional presentCase = Optional.of("example");
presentCase.isPresent();  // true

Optional emptyCase = Optional.empty();
emptyCase.isPresent();  // false

ifPresent If it has a value, it executes the argument Consumer with the value as an argument, otherwise it does nothing.

Optional presentCase = Optional.of("example");
presentCase.ifPresent(s -> {System.out.println(s)});  //To standard output"example"And output

Optional emptyCase = Optional.empty();
emptyCase.ifPresent(s -> {System.out.println(s)});  //do nothing

Get the value

get If it has a value, it returns that value, otherwise it throws a NoSuchElementException

Optional presentCase = Optional.of("example");
presentCase.get();                    // example

Optional emptyCase = Optional.empty();
emptyCase.get();                      //NoSuchElementException occurs

Use if you expect to have a value If you don't have a value and want to use the default value, you should use the following ʻor Else`

orElse If it has a value, it returns that value, otherwise it returns the value specified by the argument.

Optional presentCase = Optional.of("example");
presentCase.orElse("default");                    // example

Optional emptyCase = Optional.empty();
emptyCase.orElse("default");                      // default

orElseGet If it has a value, it returns that value, otherwise it returns the result of the Supplier specified by the argument.

Optional presentCase = Optional.of("example");
presentCase.orElseGet(() -> {"default"});          // example

Optional emptyCase = Optional.empty();
emptyCase.orElseGet(() -> {"default"});           // default

The difference from ʻorElse` is whether you pass the default value directly or express it in a lambda expression.

orElseThrow If it has a value, it returns that value, otherwise it throws an exception with the Supplier specified by the argument.

Use the value

map If it has a value, it applies the argument mapping function to that value and returns an Optional that describes the result if the result is not null. Otherwise it returns an empty Optional

Optional<String> presentCase = Optional.of("example,1,exp");
Optional<String[]> result = -> name.split(",")); // [example, 1, exp]

Optional<String> emptyCase = Optional.empty();
Optional<String[]> result = emptyCase .map(name -> name.split(",")); //Empty Optional

filter Works like a Stream API filter Returns the original Optional if the argument lambda expression condition is met, otherwise returns an empty Optional

Optional<String> presentCase =Optional.of("example");
Optional<String> match = presentCase.filter(exp -> exp.length() == 7); // "example"

Optional<String> notMatch = presentCase.filter(exp -> exp.length() != 7); //Empty Optional

Recommended Posts

Java8 to start now ~ Optional ~
Java 8 ~ Stream API ~ to start now
Java 8 to start now ~ Date time API ~
How to use java Optional
[Java] How to use Optional ②
[Java] How to use Optional ①
Java, interface to start from beginner
Java, arrays to start with beginners
I tried to summarize Java 8 now
Change List <Optional <T >> to Optional <List <T >> in Java
Introduction to java
[Java] Learn how to use Optional correctly
[Java] Optional memorandum
Java 9 Optional :: stream
Two ways to start a thread in Java + @
Changes from Java 8 to Java 11
Sum from Java_1 to 100
[Java] Connect to MySQL
View Java Optional Javadoc
Kotlin's improvements to Java
From Java to Ruby !!
Review Java annotations now
Introduction to java command
Features that are likely to enter Java 10 for now
~ I tried to learn functional programming in Java now ~
[Java] Platforms to choose from for Java development starting now (2020)
[Java] How to start a new line with StringBuilder
[Java] How to use Map
How to lower java version
Migration from Cobol to JAVA
[Java] How to use Map
Convert Java Powerpoint to XPS
Java adds table to PDF
Rewrite Java try-catch with Optional
How to uninstall Java 8 (Mac)
Java to play with Function
Java --How to make JTable
Spring + Gradle + Java Quick Start
How to handle exceptions coolly with Java 8 Stream or Optional
How to minimize Java images
How to use java class
[Java] How to use removeAll ()
[Java] How to display Wingdings
[Java] Introduction to lambda expressions
[Java] How to use string.format
I want to use the Java 8 DateTime API slowly (now)
Shell to kill Java process
I tried to make Java Optional and guard clause coexist
How to set Java constants
Connect to DB with Java
Connect to MySQL 8 with Java
[java] Reasons to use static
How to use Java variables
[Java] Introduction to Stream API
How to convert Java radix
[Java] Convert ArrayList to array
A memo to start Java programming with VS Code (2020-04 version)
Java thread to understand loosely
[Java] How to implement multithreading
How to use Lombok now
Compare Java 8 Optional with Swift