Start a personal dev blog on your domain for free with Hashnode and grow your readership.
Get Started

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.


  • 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 = -> p.getId() == id).findFirst();
  return -> 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 =, 5);

Simply we can relate,

Arrays.sort(personArray, new Comparator(<Person>(){
    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.

Start a personal dev blog on your domain for free and grow your readership.

3.4K+ developers have started their personal blogs on Hashnode in the last one month.

Write in Markdown · Publish articles on custom domain · Gain readership on day zero · Automatic GitHub backup and more

Jabiulla Shaik's photo

Nice post..

Just a question.. Do you know If we have usage of lambda expressions in Java 8 other than with Anonymous classes + Functional Interfaces ?

Ipseeta Priyadarshini's photo

Lambda expressions can be used anywhere in Java 8 where we have a target type. We have target types in the following context :

  • Variable declarations
  • Assignments
  • Return statements
  • Array initializers
  • Method or constructor arguments
  • Lambda expression bodies
  • Conditional expressions, ?:
  • Cast expressions

Very good explanation about it and thank you for help me. I will invest more time with Java SE 8 and I needed to be introduced with this code block. It´s look like Clipper 5.x SGBD program. Thank you