在Java 9中,stream()方法已新增至Optional 類別中,以改善其功能。 stream()方法可用來將Optional元素的Stream轉換為具有存在值元素的Stream。如果Optional 包含一個值,則傳回包含該值的Stream。否則,它回傳一個空 stream。
<strong>public Stream<T> stream()</strong>
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) { <strong> List<Optional<String>></strong> list = Arrays.asList( Optional.empty(), Optional.of("TutorialsPoint"), Optional.empty(), Optional.of("Tutorix")); <strong>// If optional is non-empty, get the value in stream, otherwise return empty</strong> <strong>List<String></strong> filteredListJava8 = list.stream() .<strong>flatMap</strong>(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()) .<strong>collect</strong>(Collectors.toList()); <strong>// Optional::stream method can return a stream of either one or zero element if data is present or not.</strong> <strong>List<String></strong> filteredListJava9 = list.stream() .<strong>flatMap</strong>(<strong>Optional::stream</strong>) .<strong>collect</strong>(Collectors.toList()); System.out.println(filteredListJava8); System.out.println(filteredListJava9); } }
<strong>[TutorialsPoint, Tutorix] [TutorialsPoint, Tutorix]</strong>
以上是Java 9中的Optional.stream()方法有什麼用途?的詳細內容。更多資訊請關注PHP中文網其他相關文章!