Summarize the additional elements of the Optional class in Java 9


Since I wrote it at the time of Java 8, a page summarizing the additional elements in Java 9 It's not that difficult, so I think it's okay with the articles I already have, but I'm studying so I don't care.

The article I wrote for Java 8 can be found at here.


additional elements of ifPresent

ʻIfPresentOrElse has been added this time. The False case of ʻifPresent that existed in Java 8 can now be completed with one method.

Optional<String> optional = Optional.ofNullable("");
Optional<String> optional2 =Optional.ofNullable(null);
optional.ifPresentOrElse(t -> System.out.println(true), () -> System.out.println(false));
optional2.ifPresentOrElse(t -> System.out.println(true), () -> System.out.println(false));

Add stream

From this time, it is possible to directly rewrite the Optinal class to stream.


Note that if it is null, the type will not be known unless it is set to Object type.

OK List<Object> optional = Optional.ofNullable(null).stream().collect(Collectors.toList());
OK List<String> optional = Optional.ofNullable((String)null).stream().collect(Collectors.toList());
NG List<String> optional = Optional.ofNullable(null).stream().collect(Collectors.toList());

If you want to convert List type to Stream successfully, you need to convert it to Stream with flatmap.

List<String> list = List.of("aaa", "bbb");
List<String> list2 = null;
Optional.ofNullable(list).stream().flatMap(t ->;
Optional.ofNullable(list2).stream().flatMap(t ->;

With map, you can only use the Stream type, so basically you need to use flatmap. For those of you who want to do your best with map, I lightly searched for an easy way to convert String from Stream , but I wasn't sure. Looking at the implementation of flatmap, I didn't think it should be implemented here. Let's use it obediently.

or Add method

This method does nothing if the value exists and executes only if it is Null. Since the return value is ʻOptional , is it an image that declares a substitute variable in the case of Null? Even if you want to describe a slightly complicated condition, it seems possible to express it concisely by using ʻor.

System.out.println(Optional.ofNullable("aaa").or(() -> Optional.of("bbb")).get());
System.out.println(Optional.ofNullable(null).or(() -> Optional.of("bbb")).get());

in conclusion

The JavaDoc looks like these three features have been added. I didn't see the release notes because it was troublesome, so I will add it if there is anything else.

Recommended Posts

Summarize the additional elements of the Optional class in Java 9
[Java] Delete the elements of List
Get the result of POST in Java
Examine the memory usage of Java elements
Compare the elements of an array (Java)
Examine the list of timezone IDs available in the Java ZoneId class
The story of writing Java in Emacs
Dynamically increase the number of elements in a Java 2D array (multidimensional array)
The story of low-level string comparison in Java
[Java] Handling of JavaBeans in the method chain
About the idea of anonymous classes in Java
The story of learning Java in the first programming
Measure the size of a folder in Java
Feel the passage of time even in Java
A quick review of Java learned in class
Import files of the same hierarchy in Java
First touch of the Files class (or Java 8)
[Java] Where is the implementation class of annotation that exists in Bean Validation?
Get the URL of the HTTP redirect destination in Java
[Java] Sort ArrayList with elements of your own class
A quick review of Java learned in class part4
[Ruby] The role of subscripts in learning elements in arrays
Get the name of the test case in the JUnit test class
[Java] Get the file in the jar regardless of the environment
A quick review of Java learned in class part3
A quick review of Java learned in class part2
Change the storage quality of JPEG images in Java
Use of Abstract Class and Interface properly in Java
[Java] Comparator of Collection class
Summary of Java Math class
Implementation of gzip in java
Implementation of tri-tree in Java
How to get the class name / method name running in Java
Was done in the base year of the Java calendar week
[Note] Java Output of the sum of odd and even elements
A quick explanation of the five types of static in Java
I tried to summarize the basics of kotlin and java
[Java] Try editing the elements of the Json string using the library
Count the number of digits after the decimal point in Java
How to derive the last day of the month in Java
[Java] Get date information 10 days later using milliseconds in the Date class
Guess the character code in Java
Examine the system information of AWS Lambda operating environment in Java
Various methods of Java String class
[Java] Get the dates of the past Monday and Sunday in order
[Java version] The story of serialization
Specify the java location in eclipse.ini
Output the difference between each field of two objects in Java
Handle business logic for a set of Entity in Java class
Unzip the zip file in Java
Basic usage of java Optional Part 1
StringBuffer and StringBuilder Class in Java
Mechanism and characteristics of Collection implementation class often used in Java
Various methods of the String class
List of members added in Java 9
The milliseconds to set in /lib/ of Java jre is UTC
Get the public URL of a private Flickr file in Java
Read the first 4 bytes of the Java class file and output CAFEBABE
Think about the 7 rules of Optional
Let's create a TODO application in Java 5 Switch the display of TODO
List of types added in Java 9