在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中文网其他相关文章!