changeset 7761:fa66ee11db44

invert Function.compose() to perform the provided function first.
author mduigou
date Wed, 27 Mar 2013 17:22:01 -0700
parents 1aef2a04af5c
children 0a8b1a13b916
files src/share/classes/java/util/function/Function.java test/java/util/function/FunctionsTest.java
diffstat 2 files changed, 15 insertions(+), 16 deletions(-) [+]
line wrap: on
line diff
--- a/src/share/classes/java/util/function/Function.java	Wed Mar 27 16:44:16 2013 -0700
+++ b/src/share/classes/java/util/function/Function.java	Wed Mar 27 17:22:01 2013 -0700
@@ -48,18 +48,17 @@
     public R apply(T t);
 
     /**
-     * Combine with another function returning a function which performs both
-     * functions.
+     * Compose a new function from a provided function and this function.
      *
-     * @param <V> Type of output objects from the combined function. May be the
-     * same type as {@code <U>}.
-     * @param after An additional function to be applied to the result of this
+     * @param <V> Type of input objects to the combined function. May be the
+     * same type as {@code <T>}.
+     * @param inner An additional function to be applied before this function is
+     * applied.
+     * @return A function which performs the provided function followed by this
      * function.
-     * @return A function which performs both the original function followed by
-     * a second function.
      */
-    public default <V > Function<T, V> compose(Function<? super R, ? extends V> after) {
-        Objects.requireNonNull(after);
-        return (T t) -> after.apply(apply(t));
+    public default <V > Function<V, R> compose(Function<? super V, ? extends T> inner) {
+        Objects.requireNonNull(inner);
+        return (V v) -> apply(inner.apply(v));
     }
 }
--- a/test/java/util/function/FunctionsTest.java	Wed Mar 27 16:44:16 2013 -0700
+++ b/test/java/util/function/FunctionsTest.java	Wed Mar 27 17:22:01 2013 -0700
@@ -134,14 +134,14 @@
         Function<Integer, Boolean> first = Functions.forPredicate(x -> x != 0, true, false);
         Function<Boolean, String> second = Functions.forPredicate(x -> !x, "false", "true");
         Function<Integer, String> mapper = Functions.chain(first, second);
-        Function<Integer, Integer> f1 = x -> x * 2;
+        Function<Integer, Integer> f = x ->  x % 3;
+        Function<Integer, Integer> f1 = x -> x + 3;
         Function<Integer, Integer> f2 = x -> x * 3;
-        Function<Integer, Integer> f = x ->  x % 2;
 
-        assertEquals("false", mapper.apply(0));
-        assertEquals("true", mapper.apply(1));
-        assertEquals(0, (int) Functions.chain(f1, f).compose(f1).apply(1));
-        assertEquals(3, (int) Functions.chain(f2, f).compose(f2).apply(1));
+        assertEquals(mapper.apply(0), "false");
+        assertEquals(mapper.apply(1), "true");
+        assertEquals((int) f.compose(f1).apply(7), 1);
+        assertEquals((int) f1.compose(f2).apply(1), 6);
     }
 
     @Test