dev-resources.site
for different kinds of informations.
Optional to stream in java 9
Published at
7/24/2019
Categories
java
java9
collections
optional
Author
jeetmp3
Author
7 person written this
jeetmp3
open
Last year Java 9 launched with tons of new features. In this blog post, Iām going to explain streams in Optional
(introduced in Java8). Now you can get streams to form Optional
which I think is a good feature.
Below example shows how to get a stream from Optional in Java 8 & Java 9.
package com.jbisht.blogs.java9.usingoptional;
import java.util.Optional;
import java.util.stream.Stream;
public class OptionalDemo {
public static void main(String[] args) {
// Java 9 style
getPerson().stream()
.map(Person::getName)
.map("Java 9 "::concat)
.forEach(System.out::println);
getEmptyPerson().stream()
.map(Person::getName)
.map("Java 9 "::concat)
.forEach(System.out::println);
// Java 8 Style
getPerson()
.map(Stream::of).orElseGet(Stream::empty)
.map(Person::getName)
.map("Java 8 - "::concat)
.forEach(System.out::println);
}
private static Optional<Person> getEmptyPerson() {
return Optional.empty();
}
private static Optional<Person> getPerson() {
return Optional.of(new Person("JITENDRA SINGH"));
}
static class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
Happy Coding ššš !!! If you have any feedback please comment down below.
java9 Article's
12 articles in total
Java 9 Module System
read article
Java 9 Multi-Resolution Images
read article
Java 9 Optional Improvements
read article
Java 9 TIFF Image I/O plugins
read article
Java 9 Private Interface Method
read article
Java 9 Flow API example ā Publisher and Subscriber
read article
Java 9 Factory Method for Collections: List, Set, Map
read article
Java 9 Tutorial
read article
Java 9 Flow API ā Reactive Streams
read article
Java 9 CompletableFuture API Improvements - Delay and Timeout Support
read article
Optional to stream in java 9
currently reading
Java 8 Vs. Java 9: Get Ready for a New Era
read article
Featured ones: