Currying Functions in Java with Examples

Function Currying
breaking a function with many arguments into many functions with single argument in such a way, that the output is same.
For example:
w" title="Rendered by QuickLaTeX.com" height="27" width="172" style="vertical-align: -7px;">
(v->w))" title="Rendered by QuickLaTeX.com" height="27" width="234" style="vertical-align: -7px;">
Below are some examples in Java to demonstrate Function Currying:
Example 1:
// Java Program to demonstrate Function Currying
  
import java.util.function.Function;
  
public class GFG {
    public static void main(String args[])
    {
  
        // Using Java 8 Functions
        // to create lambda expressions for functions
        // and with this, applying Function Currying
  
        // Curried Function for Adding u & v
        Function<Integer,
                 Function<Integer, Integer> >
            curryAdder = u -> v -> u + v;
  
        // Calling the curried functions
  
        // Calling Curried Function for Adding u & v
        System.out.println("Add 2, 3 :"
                           + curryAdder
                                 .apply(2)
                                 .apply(3));
  
        }
}

                    
Output:
Add 2, 3 :5
Example 2:
// Java Program to demonstrate Function Currying
  
import java.util.function.Function;
  
public class GFG {
    public static void main(String args[])
    {
  
        // Using Java 8 Functions
        // to create lambda expressions for functions
        // and with this, applying Function Currying
  
        // Curried Function for Multiplying u & v
        Function<Integer,
                 Function<Integer, Integer> >
            curryMulti = u -> v -> u * v;
  
        // Calling the curried functions
         
        // Calling Curried Function for Multiplying u & v
        System.out.println("Multiply 2, 3 :"
                           + curryMulti
                                 .apply(2)
                                 .apply(3));
    }
}

                    
Output:
Multiply 2, 3 :6
Example 3:
// Java Program to demonstrate Function Currying
  
import java.util.function.Function;
  
public class GFG {
    public static void main(String args[])
    {
  
        // Using Java 8 Functions
        // to create lambda expressions for functions
        // and with this, applying Function Currying
  
        // Curried Function for Adding u, v & w
        Function<Integer,
                 Function<Integer,
                          Function<Integer, Integer> > >
            triadder = u -> w -> v -> u + w + v;
  
        // Calling the curried functions
  
        // Calling Curried Function for Adding u, v & w
        System.out.println("Add 2, 3, 4 :"
                           + triadder
                                 .apply(2)
                                 .apply(3)
                                 .apply(4));
    }
}

                    
Output:
Add 2, 3, 4 :9


Contact Us