8050819: Please add java.util.Stream.ofNullable(T object)
Reviewed-by: alanb, smarks
--- a/jdk/src/java.base/share/classes/java/util/stream/Stream.java Tue Feb 10 14:44:33 2015 +0530
+++ b/jdk/src/java.base/share/classes/java/util/stream/Stream.java Tue Feb 10 11:18:51 2015 +0100
@@ -988,6 +988,21 @@
}
/**
+ * Returns a sequential {@code Stream} containing a single element, if
+ * non-null, otherwise returns an empty {@code Stream}.
+ *
+ * @param t the single element
+ * @param <T> the type of stream elements
+ * @return a stream with a single element if the specified element
+ * is non-null, otherwise an empty stream
+ * @since 1.9
+ */
+ public static<T> Stream<T> ofNullable(T t) {
+ return t == null ? Stream.empty()
+ : StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
+ }
+
+ /**
* Returns a sequential ordered stream whose elements are the specified values.
*
* @param <T> the type of stream elements
--- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamBuilderTest.java Tue Feb 10 14:44:33 2015 +0530
+++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamBuilderTest.java Tue Feb 10 11:18:51 2015 +0100
@@ -55,8 +55,30 @@
@Test
+ public void testOfNullableWithNonNull() {
+ TestData.OfRef<Integer> data = TestData.Factory.ofSupplier("{1}",
+ () -> Stream.ofNullable(1));
+
+ withData(data).
+ stream(s -> s).
+ expectedResult(Collections.singletonList(1)).
+ exercise();
+ }
+
+ @Test
+ public void testOfNullableWithNull() {
+ TestData.OfRef<Integer> data = TestData.Factory.ofSupplier("{null})",
+ () -> Stream.ofNullable(null));
+
+ withData(data).
+ stream(s -> s).
+ expectedResult(Collections.emptyList()).
+ exercise();
+ }
+
+ @Test
public void testSingleton() {
- TestData.OfRef<Integer> data = TestData.Factory.ofSupplier("[0, 1)",
+ TestData.OfRef<Integer> data = TestData.Factory.ofSupplier("{1}",
() -> Stream.of(1));
withData(data).
@@ -118,7 +140,7 @@
@Test
public void testIntSingleton() {
- TestData.OfInt data = TestData.Factory.ofIntSupplier("[0, 1)",
+ TestData.OfInt data = TestData.Factory.ofIntSupplier("{1}",
() -> IntStream.of(1));
withData(data).
@@ -180,7 +202,7 @@
@Test
public void testLongSingleton() {
- TestData.OfLong data = TestData.Factory.ofLongSupplier("[0, 1)",
+ TestData.OfLong data = TestData.Factory.ofLongSupplier("{1}",
() -> LongStream.of(1));
withData(data).
@@ -242,7 +264,7 @@
@Test
public void testDoubleSingleton() {
- TestData.OfDouble data = TestData.Factory.ofDoubleSupplier("[0, 1)", () -> DoubleStream.of(1));
+ TestData.OfDouble data = TestData.Factory.ofDoubleSupplier("{1}", () -> DoubleStream.of(1));
withData(data).
stream(s -> s).