Anonymous functions in Java - Explained!

Anonymous functions in Java - Explained!

If you mean anonymous function (function literal, lambda abstraction) then you are using a Java 8 version.

What is an anonymous function?

Anonymous function is a function definition that is not bound to an identifier. These are a form of nested function, in allowing access to variables in the scope of the containing function (non-local functions). This means anonymous functions need to be implemented using closures. Simply, lambda is an anonymous function which can be passed around in a concise way.

A lambda expression represents an anonymous function. It comprises of a set of parameters, a lambda operator (->) and a function body.

Return Type

  1. When there is a single statement, the return type of the anonymous function is the same as that of the body expression.
  2. When there is more than one statement enclosed in curly brackets then the return type of the anonymous function is the same as the type of the value returned within the code block, or void if nothing is returned.

Examples

  • Zero parameter

() -> System.out.println("No Params");

  • One Parameter

(param) -> System.out.println("One parameter: " + param);

or without parenthesis;

param -> param (Identity function example)

  • Multiple parameters

(param1, param2) -> param1 + param2;

  • Parameter Types

(int i, String name) -> System.out.println("id:" + i + " name:" + name);

  • Code block

(param1, param2) -> { return param1 + param2; }

  • Nested lambda expression :Two nested expressions with the first one as closure
(id, defaultPrice) -> {
  Optional<Product> product = productList.stream().filter(p -> p.getId() == id).findFirst();
  return product.map(p -> p.getPrice()).orElse(defaultPrice);
}
  • As objects : the lambda expression is assigned to variable, and finally it is invoked by invoking the interface method it implements
public interface MyComparator {
    public boolean compare(int a1, int a2);
}

MyComparator myComparator = (a1, a2) -> return a1 > a2;
boolean result = myComparator.compare(2, 5);

Simply we can relate,

Arrays.sort(personArray, new Comparator(<Person>(){
    @Override
    public int compare(Person p1, Person p2){
        return p1.getAge() - p2.getAge();
    }
});

becomes ->

Arrays.sort(personArray, (p1,p2) -> p1.getAge() - p2.getAge());

Lambda expressions as functional interfaces

Interfaces that contain only one abstract method in addition to one or more default or static methods.

public class Calculator {
    interface IntegerMath {
        int operation(int a, int b);

        default IntegerMath swap() {
          return (a, b) -> operation(b, a);
        }
    }
    private static int apply(int a, int b, IntegerMath op) {
        return op.operation(a, b);
    }

    public static void main(String... args) {
        IntegerMath addition = (a, b) -> a + b;
        IntegerMath subtraction = (a, b) -> a - b;
        System.out.println("40 + 2 = " + apply(40, 2, addition));
        System.out.println("20 - 10 = " + apply(20, 10, subtraction));
        System.out.println("10 - 20 = " + apply(20, 10, subtraction.swap()));    
    }

Here IntegerMath is a functional interface with default method swap. Lambda expressions that implement IntegerMath are passed to the apply() method to be executed.

Did you find this article valuable?

Support Ipseeta Priyadarshini by becoming a sponsor. Any amount is appreciated!