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.
JavaDoc http://download.java.net/java/jdk9/docs/api/java/util/Optional.html
ʻ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));
result:
true
false
From this time, it is possible to directly rewrite the Optinal class to stream.
Optional.ofNullable(null).stream().forEach(System.out::println);
result:
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 -> t.stream()).forEach(System.out::println);
Optional.ofNullable(list2).stream().flatMap(t -> t.stream()).forEach(System.out::println);
result:
aaa
bbb
With map
, you can only use the Stream 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 flatmap
, I didn't think it should be implemented here.
Let's use it obediently.
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());
result:
aaa
bbb
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