

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the use of the Optional.stream() method in Java 9?
In Java 9, the stream() method has been added to the Optional class to improve its functionality. The stream() method can be used to transform a Stream of optional elements to a Stream of present value elements. If the Optional contains a value, then return a Stream containing the value. Otherwise, it returns an empty stream.
Syntax
public Stream<T> stream()
Example
import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; public class StreamMethodTest { public static void main(String[] args) { List<Optional<String>> list = Arrays.asList( Optional.empty(), Optional.of("TutorialsPoint"), Optional.empty(), Optional.of("Tutorix")); // If optional is non-empty, get the value in stream, otherwise return empty List<String> filteredListJava8 = list.stream() .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()) .collect(Collectors.toList()); // Optional::stream method can return a stream of either one or zero element if data is present or not. List<String> filteredListJava9 = list.stream() .flatMap(Optional::stream) .collect(Collectors.toList()); System.out.println(filteredListJava8); System.out.println(filteredListJava9); } }
Output
[TutorialsPoint, Tutorix] [TutorialsPoint, Tutorix]
- Related Questions & Answers
- What is the use of the toEpochSecond() method in Java 9?
- What is the use of the Cleaner class in Java 9?
- What is the use of the jdeprscan tool in Java 9?
- What is the use of underscore keyword in Java 9?
- What is the use of the Tab key in JShell in Java 9?
- What is the purpose of using Optional.ifPresentOrElse() method in Java 9?
- What is the use of setBounds() method in Java?
- What is the use of Thread.sleep() method in Java?
- When to use the ofNullable() method of Stream in Java 9?
- When to use the readNBytes() method of InputStream in Java 9?
- When to use the readAllBytes() method of InputStream in Java 9?
- When to use the delayedExecutor() method of CompletableFuture in Java 9?
- What is the use of a multi-version compatible jar in Java 9?
- What is the importance of REPL in Java 9?
- What is the importance of the ProcessHandle interface in Java 9?
Advertisements