--- old/src/share/classes/java/util/Optional.java 2013-07-05 14:22:40.230155906 -0700 +++ new/src/share/classes/java/util/Optional.java 2013-07-05 14:22:40.058155909 -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 Optional 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 filter(Predicate 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}: + * + *
{@code
+     *     Optional fis =
+     *         names.stream().filter(name -> !isProcessedYet(name))
+     *                       .findFirst()
+     *                       .map(name -> new FileInputStream(name));
+     * }
+ * + * Here, {@code findFirst} returns an {@code Optional}, and then + * {@code map} returns an {@code Optional} for the desired + * file if one exists. + * + * @param 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 Optional map(Function 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 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 Optional flatMap(Function> 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 --- old/src/share/classes/java/util/OptionalDouble.java 2013-07-05 14:22:41.122155890 -0700 +++ new/src/share/classes/java/util/OptionalDouble.java 2013-07-05 14:22:40.946155893 -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: *
    - *
  • it is also an {@code OptionalInt} and; + *
  • it is also an {@code OptionalDouble} and; *
  • both instances have no value present or; *
  • the present values are "equal to" each other via {@code Double.compare() == 0}. *
@@ -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 --- old/src/share/classes/java/util/OptionalInt.java 2013-07-05 14:22:41.942155876 -0700 +++ new/src/share/classes/java/util/OptionalInt.java 2013-07-05 14:22:41.770155879 -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: *
    *
  • 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 --- old/src/share/classes/java/util/OptionalLong.java 2013-07-05 14:22:42.758155861 -0700 +++ new/src/share/classes/java/util/OptionalLong.java 2013-07-05 14:22:42.590155864 -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: *
      - *
    • it is also an {@code OptionalInt} and; + *
    • it is also an {@code OptionalLong} and; *
    • both instances have no value present or; *
    • the present values are "equal to" each other via {@code ==}. *
    @@ -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 --- old/test/java/util/Optional/Basic.java 2013-07-05 14:22:43.582155846 -0700 +++ new/test/java/util/Optional/Basic.java 2013-07-05 14:22:43.402155850 -0700 @@ -58,36 +58,36 @@ assertSame(Boolean.FALSE, empty.orElseGet(()-> Boolean.FALSE)); } - @Test(expectedExceptions=NoSuchElementException.class) - public void testEmptyGet() { - Optional empty = Optional.empty(); + @Test(expectedExceptions=NoSuchElementException.class) + public void testEmptyGet() { + Optional empty = Optional.empty(); - Boolean got = empty.get(); - } + Boolean got = empty.get(); + } - @Test(expectedExceptions=NullPointerException.class) - public void testEmptyOrElseGetNull() { - Optional empty = Optional.empty(); + @Test(expectedExceptions=NullPointerException.class) + public void testEmptyOrElseGetNull() { + Optional empty = Optional.empty(); - Boolean got = empty.orElseGet(null); - } + Boolean got = empty.orElseGet(null); + } - @Test(expectedExceptions=NullPointerException.class) - public void testEmptyOrElseThrowNull() throws Throwable { - Optional empty = Optional.empty(); + @Test(expectedExceptions=NullPointerException.class) + public void testEmptyOrElseThrowNull() throws Throwable { + Optional empty = Optional.empty(); - Boolean got = empty.orElseThrow(null); - } + Boolean got = empty.orElseThrow(null); + } - @Test(expectedExceptions=ObscureException.class) - public void testEmptyOrElseThrow() throws Exception { - Optional empty = Optional.empty(); + @Test(expectedExceptions=ObscureException.class) + public void testEmptyOrElseThrow() throws Exception { + Optional 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 empty = Optional.empty(); Optional presentEmptyString = Optional.of(""); Optional present = Optional.of(Boolean.TRUE); @@ -116,6 +116,116 @@ assertSame(Boolean.TRUE, present.orElseThrow(ObscureException::new)); } + @Test(groups = "unit") + public void testOfNullable() { + Optional 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 empty = Optional.empty(); + Optional duke = Optional.of("Duke"); + + try { + Optional result = empty.filter(null); + fail("Should throw NPE on null mapping function"); + } catch (NullPointerException npe) { + // expected + } + + Optional 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 emptyString = Optional.of(""); + result = emptyString.filter(String::isEmpty); + assertTrue(result.isPresent()); + assertEquals(result.get(), ""); + } + + @Test(groups = "unit") + public void testMap() { + Optional empty = Optional.empty(); + Optional duke = Optional.of("Duke"); + + // Null mapper function + try { + Optional b = empty.map(null); + fail("Should throw NPE on null mapping function"); + } catch (NullPointerException npe) { + // expected + } + + // Map an empty value + Optional 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 l = duke.map(String::length); + assertEquals(l.get().intValue(), 4); + } + + @Test(groups = "unit") + public void testFlatMap() { + Optional empty = Optional.empty(); + Optional duke = Optional.of("Duke"); + + // Null mapper function + try { + Optional b = empty.flatMap(null); + fail("Should throw NPE on null mapping function"); + } catch (NullPointerException npe) { + // expected + } + + // Map into null + try { + Optional 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 b = empty.flatMap(s -> null); + assertFalse(b.isPresent()); + } catch (NullPointerException npe) { + fail("Mapper function should not be invoked"); + } + + // Map an empty value + Optional l = empty.flatMap(s -> Optional.of(s.length())); + assertFalse(l.isPresent()); + + // Map to value + Optional 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 { }