提交 477f1cc7 编写于 作者: M mduigou

8015317: Optional.filter, map, and flatMap

Reviewed-by: psandoz, mduigou
Contributed-by: brian.goetz@oracle.com, henry.jen@oracle.com
上级 d11eedbf
...@@ -25,6 +25,8 @@ ...@@ -25,6 +25,8 @@
package java.util; package java.util;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier; import java.util.function.Supplier;
/** /**
...@@ -52,7 +54,7 @@ public final class Optional<T> { ...@@ -52,7 +54,7 @@ public final class Optional<T> {
private final T value; private final T value;
/** /**
* Construct an empty instance. * Constructs an empty instance.
* *
* @implNote Generally only one empty instance, {@link Optional#EMPTY}, * @implNote Generally only one empty instance, {@link Optional#EMPTY},
* should exist per VM. * should exist per VM.
...@@ -80,7 +82,7 @@ public final class Optional<T> { ...@@ -80,7 +82,7 @@ public final class Optional<T> {
} }
/** /**
* Construct an instance with the value present. * Constructs an instance with the value present.
* *
* @param value the non-null value to be present * @param value the non-null value to be present
*/ */
...@@ -89,7 +91,7 @@ public final class Optional<T> { ...@@ -89,7 +91,7 @@ public final class Optional<T> {
} }
/** /**
* 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 * @param value the value to be present, which must be non-null
* @return an {@code Optional} with the value present * @return an {@code Optional} with the value present
...@@ -98,6 +100,18 @@ public final class Optional<T> { ...@@ -98,6 +100,18 @@ public final class Optional<T> {
return new Optional<>(value); return new Optional<>(value);
} }
/**
* 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, * If a value is present in this {@code Optional}, returns the value,
* otherwise throws {@code NoSuchElementException}. * otherwise throws {@code NoSuchElementException}.
...@@ -124,7 +138,7 @@ public final class Optional<T> { ...@@ -124,7 +138,7 @@ public final class Optional<T> {
} }
/** /**
* 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. * otherwise do nothing.
* *
* @param consumer block to be executed if a value is present * @param consumer block to be executed if a value is present
...@@ -136,6 +150,89 @@ public final class Optional<T> { ...@@ -136,6 +150,89 @@ public final class Optional<T> {
consumer.accept(value); consumer.accept(value);
} }
/**
* 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}. * Return the value if present, otherwise return {@code other}.
* *
......
...@@ -186,10 +186,10 @@ public final class OptionalDouble { ...@@ -186,10 +186,10 @@ public final class OptionalDouble {
} }
/** /**
* 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: * other object is considered equal if:
* <ul> * <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>both instances have no value present or;
* <li>the present values are "equal to" each other via {@code Double.compare() == 0}. * <li>the present values are "equal to" each other via {@code Double.compare() == 0}.
* </ul> * </ul>
...@@ -226,12 +226,14 @@ public final class OptionalDouble { ...@@ -226,12 +226,14 @@ public final class OptionalDouble {
} }
/** /**
* 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 * debugging. The exact presentation format is unspecified and may vary
* between implementations and versions. * between implementations and versions.
* *
* @implSpec If a value is present the result must include its string * @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. * unambiguously differentiable.
* *
* @return the string representation of this instance * @return the string representation of this instance
......
...@@ -186,7 +186,7 @@ public final class OptionalInt { ...@@ -186,7 +186,7 @@ public final class OptionalInt {
} }
/** /**
* 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: * other object is considered equal if:
* <ul> * <ul>
* <li>it is also an {@code OptionalInt} and; * <li>it is also an {@code OptionalInt} and;
...@@ -226,12 +226,14 @@ public final class OptionalInt { ...@@ -226,12 +226,14 @@ public final class OptionalInt {
} }
/** /**
* 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 * debugging. The exact presentation format is unspecified and may vary
* between implementations and versions. * between implementations and versions.
* *
* @implSpec If a value is present the result must include its string * @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. * unambiguously differentiable.
* *
* @return the string representation of this instance * @return the string representation of this instance
......
...@@ -186,10 +186,10 @@ public final class OptionalLong { ...@@ -186,10 +186,10 @@ public final class OptionalLong {
} }
/** /**
* 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: * other object is considered equal if:
* <ul> * <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>both instances have no value present or;
* <li>the present values are "equal to" each other via {@code ==}. * <li>the present values are "equal to" each other via {@code ==}.
* </ul> * </ul>
...@@ -226,12 +226,14 @@ public final class OptionalLong { ...@@ -226,12 +226,14 @@ public final class OptionalLong {
} }
/** /**
* 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 * debugging. The exact presentation format is unspecified and may vary
* between implementations and versions. * between implementations and versions.
* *
* @implSpec If a value is present the result must include its string * @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. * unambiguously differentiable.
* *
* @return the string representation of this instance * @return the string representation of this instance
......
...@@ -116,6 +116,116 @@ public class Basic { ...@@ -116,6 +116,116 @@ public class Basic {
assertSame(Boolean.TRUE, present.<RuntimeException>orElseThrow(ObscureException::new)); 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 { private static class ObscureException extends RuntimeException {
} }
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册