src/share/classes/java/util/function/Function.java
Print this page
rev 7047 : 8004015: Additional static and instance utils for functional interfaces.
Reviewed-by: briangoetz
@@ -22,18 +22,19 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util.function;
+import java.util.Objects;
/**
* Apply a function to the input argument, yielding an appropriate result. A
* function may variously provide a mapping between types, object instances or
* keys and values or any other form of transformation upon the input.
*
- * @param <T> the type of the input to the {@code apply} operation.
- * @param <R> the type of the result of the {@code apply} operation.
+ * @param <T> the type of the input to the {@code apply} operation
+ * @param <R> the type of the result of the {@code apply} operation
*
* @since 1.8
*/
@FunctionalInterface
public interface Function<T, R> {
@@ -42,7 +43,50 @@
* Compute the result of applying the function to the input argument
*
* @param t the input object
* @return the function result
*/
- public R apply(T t);
+ R apply(T t);
+
+ /**
+ * Compose a new function which applies the provided function followed by
+ * this function.
+ *
+ * @param <V> Type of input objects to the combined function. May be the
+ * same type as {@code <T>} or {@code <R>}
+ * @param before An additional function to be applied before this function
+ * is applied
+ * @return A function which performs the provided function followed by this
+ * function
+ * @throws NullPointerException if before is null
+ */
+ default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
+ Objects.requireNonNull(before);
+ return (V v) -> apply(before.apply(v));
+ }
+
+ /**
+ * Compose a new function which applies this function followed by the
+ * provided function.
+ *
+ * @param <V> Type of output objects to the combined function. May be the
+ * same type as {@code <T>} or {@code <R>}
+ * @param after An additional function to be applied after this function is
+ * applied
+ * @return A function which performs this function followed by the provided
+ * function followed
+ * @throws NullPointerException if after is null
+ */
+ default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
+ Objects.requireNonNull(after);
+ return (T t) -> after.apply(apply(t));
+ }
+
+ /**
+ * Returns a {@code Function} whose {@code apply} method returns its input.
+ *
+ * @param <T> the type of the input and output objects to the function
+ */
+ static <T> Function<T, T> identity() {
+ return t -> t;
+ }
}