8015317: Optional.filter, map, and flatMap
authormduigou
Fri, 12 Jul 2013 11:12:16 -0700
changeset 18819 c4335fc31aeb
parent 18818 a9ceff754226
child 18820 a87cdd6a8834
8015317: Optional.filter, map, and flatMap Reviewed-by: psandoz, mduigou Contributed-by: brian.goetz@oracle.com, henry.jen@oracle.com
jdk/src/share/classes/java/util/Optional.java
jdk/src/share/classes/java/util/OptionalDouble.java
jdk/src/share/classes/java/util/OptionalInt.java
jdk/src/share/classes/java/util/OptionalLong.java
jdk/test/java/util/Optional/Basic.java
--- a/jdk/src/share/classes/java/util/Optional.java	Fri Jul 12 11:11:30 2013 -0700
+++ b/jdk/src/share/classes/java/util/Optional.java	Fri Jul 12 11:12:16 2013 -0700
@@ -25,6 +25,8 @@
 package java.util;
 
 import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.function.Predicate;
 import java.util.function.Supplier;
 
 /**
@@ -52,7 +54,7 @@
     private final T value;
 
     /**
-     * Construct an empty instance.
+     * Constructs an empty instance.
      *
      * @implNote Generally only one empty instance, {@link Optional#EMPTY},
      * should exist per VM.
@@ -80,7 +82,7 @@
     }
 
     /**
-     * Construct an instance with the value present.
+     * Constructs an instance with the value present.
      *
      * @param value the non-null value to be present
      */
@@ -89,7 +91,7 @@
     }
 
     /**
-     * Return an {@code Optional} with the specified present value.
+     * Returns an {@code Optional} with the specified present non-null value.
      *
      * @param value the value to be present, which must be non-null
      * @return an {@code Optional} with the value present
@@ -99,6 +101,18 @@
     }
 
     /**
+     * Returns an {@code Optional} describing the specified value, if non-null,
+     * otherwise returns an empty {@code Optional}.
+     *
+     * @param value the possibly-null value to describe
+     * @return an {@code Optional} with a present value if the specified value
+     * is non-null, otherwise an empty {@code Optional}
+     */
+    public static <T> Optional<T> ofNullable(T value) {
+        return value == null ? empty() : of(value);
+    }
+
+    /**
      * If a value is present in this {@code Optional}, returns the value,
      * otherwise throws {@code NoSuchElementException}.
      *
@@ -124,7 +138,7 @@
     }
 
     /**
-     * Have the specified consumer accept the value if a value is present,
+     * If a value is present, invoke the specified consumer with the value,
      * otherwise do nothing.
      *
      * @param consumer block to be executed if a value is present
@@ -137,6 +151,89 @@
     }
 
     /**
+     * If a value is present, and the value matches the given predicate,
+     * return an {@code Optional} describing the value, otherwise return an
+     * empty {@code Optional}.
+     *
+     * @param predicate a predicate to apply to the value, if present
+     * @return an {@code Optional} describing the value of this {@code Optional}
+     * if a value is present and the value matches the given predicate,
+     * otherwise an empty {@code Optional}
+     * @throws NullPointerException if the predicate is null
+     */
+    public Optional<T> filter(Predicate<? super T> predicate) {
+        Objects.requireNonNull(predicate);
+        if (!isPresent())
+            return this;
+        else
+            return predicate.test(value) ? this : empty();
+    }
+
+    /**
+     * If a value is present, apply the provided mapping function to it,
+     * and if the result is non-null, return an {@code Optional} describing the
+     * result.  Otherwise return an empty {@code Optional}.
+     *
+     * @apiNote This method supports post-processing on optional values, without
+     * the need to explicitly check for a return status.  For example, the
+     * following code traverses a stream of file names, selects one that has
+     * not yet been processed, and then opens that file, returning an
+     * {@code Optional<FileInputStream>}:
+     *
+     * <pre>{@code
+     *     Optional<FileInputStream> fis =
+     *         names.stream().filter(name -> !isProcessedYet(name))
+     *                       .findFirst()
+     *                       .map(name -> new FileInputStream(name));
+     * }</pre>
+     *
+     * Here, {@code findFirst} returns an {@code Optional<String>}, and then
+     * {@code map} returns an {@code Optional<FileInputStream>} for the desired
+     * file if one exists.
+     *
+     * @param <U> The type of the result of the mapping function
+     * @param mapper a mapping function to apply to the value, if present
+     * @return an {@code Optional} describing the result of applying a mapping
+     * function to the value of this {@code Optional}, if a value is present,
+     * otherwise an empty {@code Optional}
+     * @throws NullPointerException if the mapping function is null
+     */
+    public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
+        Objects.requireNonNull(mapper);
+        if (!isPresent())
+            return empty();
+        else {
+            return Optional.ofNullable(mapper.apply(value));
+        }
+    }
+
+    /**
+     * If a value is present, apply the provided {@code Optional}-bearing
+     * mapping function to it, return that result, otherwise return an empty
+     * {@code Optional}.  This method is similar to {@link #map(Function)},
+     * but the provided mapper is one whose result is already an {@code Optional},
+     * and if invoked, {@code flatMap} does not wrap it with an additional
+     * {@code Optional}.
+     *
+     * @param <U> The type parameter to the {@code Optional} returned by
+     * @param mapper a mapping function to apply to the value, if present
+     *           the mapping function
+     * @return the result of applying an {@code Optional}-bearing mapping
+     * function to the value of this {@code Optional}, if a value is present,
+     * otherwise an empty {@code Optional}
+     * @throws NullPointerException if the mapping function is null or returns
+     * a null result
+     */
+    public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
+        Objects.requireNonNull(mapper);
+        if (!isPresent())
+            return empty();
+        else {
+            return Objects.requireNonNull(mapper.apply(value));
+        }
+    }
+
+    /**
      * Return the value if present, otherwise return {@code other}.
      *
      * @param other the value to be returned if there is no value present, may
--- a/jdk/src/share/classes/java/util/OptionalDouble.java	Fri Jul 12 11:11:30 2013 -0700
+++ b/jdk/src/share/classes/java/util/OptionalDouble.java	Fri Jul 12 11:12:16 2013 -0700
@@ -186,10 +186,10 @@
     }
 
     /**
-     * Indicates whether some other object is "equal to" this Optional. The
+     * Indicates whether some other object is "equal to" this OptionalDouble. The
      * other object is considered equal if:
      * <ul>
-     * <li>it is also an {@code OptionalInt} and;
+     * <li>it is also an {@code OptionalDouble} and;
      * <li>both instances have no value present or;
      * <li>the present values are "equal to" each other via {@code Double.compare() == 0}.
      * </ul>
@@ -226,12 +226,14 @@
     }
 
     /**
-     * Returns a non-empty string representation of this OptionalDouble suitable for
+     * {@inheritDoc}
+     *
+     * Returns a non-empty string representation of this object suitable for
      * debugging. The exact presentation format is unspecified and may vary
      * between implementations and versions.
      *
      * @implSpec If a value is present the result must include its string
-     * representation in the result. Empty and present OptionalDoubless must be
+     * representation in the result. Empty and present instances must be
      * unambiguously differentiable.
      *
      * @return the string representation of this instance
--- a/jdk/src/share/classes/java/util/OptionalInt.java	Fri Jul 12 11:11:30 2013 -0700
+++ b/jdk/src/share/classes/java/util/OptionalInt.java	Fri Jul 12 11:12:16 2013 -0700
@@ -186,7 +186,7 @@
     }
 
     /**
-     * Indicates whether some other object is "equal to" this Optional. The
+     * Indicates whether some other object is "equal to" this OptionalInt. The
      * other object is considered equal if:
      * <ul>
      * <li>it is also an {@code OptionalInt} and;
@@ -226,12 +226,14 @@
     }
 
     /**
-     * Returns a non-empty string representation of this OptionalInt suitable for
+     * {@inheritDoc}
+     *
+     * Returns a non-empty string representation of this object suitable for
      * debugging. The exact presentation format is unspecified and may vary
      * between implementations and versions.
      *
      * @implSpec If a value is present the result must include its string
-     * representation in the result. Empty and present OptionalInts must be
+     * representation in the result. Empty and present instances must be
      * unambiguously differentiable.
      *
      * @return the string representation of this instance
--- a/jdk/src/share/classes/java/util/OptionalLong.java	Fri Jul 12 11:11:30 2013 -0700
+++ b/jdk/src/share/classes/java/util/OptionalLong.java	Fri Jul 12 11:12:16 2013 -0700
@@ -186,10 +186,10 @@
     }
 
     /**
-     * Indicates whether some other object is "equal to" this Optional. The
+     * Indicates whether some other object is "equal to" this OptionalLong. The
      * other object is considered equal if:
      * <ul>
-     * <li>it is also an {@code OptionalInt} and;
+     * <li>it is also an {@code OptionalLong} and;
      * <li>both instances have no value present or;
      * <li>the present values are "equal to" each other via {@code ==}.
      * </ul>
@@ -226,12 +226,14 @@
     }
 
     /**
-     * Returns a non-empty string representation of this OptionalLong suitable for
+     * {@inheritDoc}
+     *
+     * Returns a non-empty string representation of this object suitable for
      * debugging. The exact presentation format is unspecified and may vary
      * between implementations and versions.
      *
      * @implSpec If a value is present the result must include its string
-     * representation in the result. Empty and present OptionalLongs must be
+     * representation in the result. Empty and present instances must be
      * unambiguously differentiable.
      *
      * @return the string representation of this instance
--- a/jdk/test/java/util/Optional/Basic.java	Fri Jul 12 11:11:30 2013 -0700
+++ b/jdk/test/java/util/Optional/Basic.java	Fri Jul 12 11:12:16 2013 -0700
@@ -58,36 +58,36 @@
         assertSame(Boolean.FALSE, empty.orElseGet(()-> Boolean.FALSE));
     }
 
-        @Test(expectedExceptions=NoSuchElementException.class)
-        public void testEmptyGet() {
-            Optional<Boolean> empty = Optional.empty();
+    @Test(expectedExceptions=NoSuchElementException.class)
+    public void testEmptyGet() {
+        Optional<Boolean> empty = Optional.empty();
 
-            Boolean got = empty.get();
-        }
+        Boolean got = empty.get();
+    }
 
-        @Test(expectedExceptions=NullPointerException.class)
-        public void testEmptyOrElseGetNull() {
-            Optional<Boolean> empty = Optional.empty();
+    @Test(expectedExceptions=NullPointerException.class)
+    public void testEmptyOrElseGetNull() {
+        Optional<Boolean> empty = Optional.empty();
 
-            Boolean got = empty.orElseGet(null);
-        }
+        Boolean got = empty.orElseGet(null);
+    }
 
-        @Test(expectedExceptions=NullPointerException.class)
-        public void testEmptyOrElseThrowNull() throws Throwable {
-            Optional<Boolean> empty = Optional.empty();
+    @Test(expectedExceptions=NullPointerException.class)
+    public void testEmptyOrElseThrowNull() throws Throwable {
+        Optional<Boolean> empty = Optional.empty();
 
-            Boolean got = empty.orElseThrow(null);
-        }
+        Boolean got = empty.orElseThrow(null);
+    }
 
-        @Test(expectedExceptions=ObscureException.class)
-        public void testEmptyOrElseThrow() throws Exception {
-            Optional<Boolean> empty = Optional.empty();
+    @Test(expectedExceptions=ObscureException.class)
+    public void testEmptyOrElseThrow() throws Exception {
+        Optional<Boolean> empty = Optional.empty();
 
-            Boolean got = empty.orElseThrow(ObscureException::new);
-        }
+        Boolean got = empty.orElseThrow(ObscureException::new);
+    }
 
-        @Test(groups = "unit")
-        public void testPresent() {
+    @Test(groups = "unit")
+    public void testPresent() {
         Optional<Boolean> empty = Optional.empty();
         Optional<String> presentEmptyString = Optional.of("");
         Optional<Boolean> present = Optional.of(Boolean.TRUE);
@@ -116,6 +116,116 @@
         assertSame(Boolean.TRUE, present.<RuntimeException>orElseThrow(ObscureException::new));
     }
 
+    @Test(groups = "unit")
+    public void testOfNullable() {
+        Optional<String> instance = Optional.ofNullable(null);
+        assertFalse(instance.isPresent());
+
+        instance = Optional.ofNullable("Duke");
+        assertTrue(instance.isPresent());
+        assertEquals(instance.get(), "Duke");
+    }
+
+    @Test(groups = "unit")
+    public void testFilter() {
+        // Null mapper function
+        Optional<String> empty = Optional.empty();
+        Optional<String> duke = Optional.of("Duke");
+
+        try {
+            Optional<String> result = empty.filter(null);
+            fail("Should throw NPE on null mapping function");
+        } catch (NullPointerException npe) {
+            // expected
+        }
+
+        Optional<String> result = empty.filter(String::isEmpty);
+        assertFalse(result.isPresent());
+
+        result = duke.filter(String::isEmpty);
+        assertFalse(result.isPresent());
+        result = duke.filter(s -> s.startsWith("D"));
+        assertTrue(result.isPresent());
+        assertEquals(result.get(), "Duke");
+
+        Optional<String> emptyString = Optional.of("");
+        result = emptyString.filter(String::isEmpty);
+        assertTrue(result.isPresent());
+        assertEquals(result.get(), "");
+    }
+
+    @Test(groups = "unit")
+    public void testMap() {
+        Optional<String> empty = Optional.empty();
+        Optional<String> duke = Optional.of("Duke");
+
+        // Null mapper function
+        try {
+            Optional<Boolean> b = empty.map(null);
+            fail("Should throw NPE on null mapping function");
+        } catch (NullPointerException npe) {
+            // expected
+        }
+
+        // Map an empty value
+        Optional<Boolean> b = empty.map(String::isEmpty);
+        assertFalse(b.isPresent());
+
+        // Map into null
+        b = empty.map(n -> null);
+        assertFalse(b.isPresent());
+        b = duke.map(s -> null);
+        assertFalse(b.isPresent());
+
+        // Map to value
+        Optional<Integer> l = duke.map(String::length);
+        assertEquals(l.get().intValue(), 4);
+    }
+
+    @Test(groups = "unit")
+    public void testFlatMap() {
+        Optional<String> empty = Optional.empty();
+        Optional<String> duke = Optional.of("Duke");
+
+        // Null mapper function
+        try {
+            Optional<Boolean> b = empty.flatMap(null);
+            fail("Should throw NPE on null mapping function");
+        } catch (NullPointerException npe) {
+            // expected
+        }
+
+        // Map into null
+        try {
+            Optional<Boolean> b = duke.flatMap(s -> null);
+            fail("Should throw NPE when mapper return null");
+        } catch (NullPointerException npe) {
+            // expected
+        }
+
+        // Empty won't invoke mapper function
+        try {
+            Optional<Boolean> b = empty.flatMap(s -> null);
+            assertFalse(b.isPresent());
+        } catch (NullPointerException npe) {
+            fail("Mapper function should not be invoked");
+        }
+
+        // Map an empty value
+        Optional<Integer> l = empty.flatMap(s -> Optional.of(s.length()));
+        assertFalse(l.isPresent());
+
+        // Map to value
+        Optional<Integer> fixture = Optional.of(Integer.MAX_VALUE);
+        l = duke.flatMap(s -> Optional.of(s.length()));
+        assertTrue(l.isPresent());
+        assertEquals(l.get().intValue(), 4);
+
+        // Verify same instance
+        l = duke.flatMap(s -> fixture);
+        assertSame(l, fixture);
+    }
+
     private static class ObscureException extends RuntimeException {
 
     }