Func and Action Equivalent in Java

This tutorial will show you how to achieve Func and Action functionality in Java.

Introduction

Java doesn’t have exactly delegate type like C#, hence there are no Func and Action feature either. However, since Java 8 this feature can be achieved through combination of Functional Interface, Method Reference, or Lambda Expression.

Delegate

Delegate can be achieved by combining Functional Interface and Method Reference.

Functional Interface

Functional Interface is an interface that has only one abstract method. You can write the interface like usual or it is better to add @FunctionalInterface attribute to enforce the interface as Functional Interface. This way, if you add additional abstract method, it would raise an error.

Below is the example:

@FunctionalInterface
interface Drawable {
    void Draw();
}

Method Reference

Method Reference has syntax Class::method to get the reference of the method. It supports instance method, static method, and constructor.

From C# point of view, it looks like delegate but it needs to be combined with Functional Interface since delegate type doesn’t exist in Java.

Below is the example:

@FunctionalInterface
interface Drawable {
    void Draw();
}

public class App {
    public static void main(String[] args) throws Exception {
        Drawable drawable = App::print;
        drawable.Draw();
    }

    public static void print(){
        System.out.println("Printing from App class");
    }
}

Above Java code is equivalent to following delegate code in C#.

class App
{
    public delegate void Draw();

    public static void Main(string[] args)
    {
        Draw del = App.Print;
        del();
    }

    public static void Print()
    {
        Console.WriteLine("Printing from App class");
    }
}

You must notice that Functional Interface is what makes the difference and acts as a delegate in Java.

Func and Action

Func and Action can be achieved by combining Functional Interface and Lambda Expression.

Here, Functional Interface acts as delegate while Lambda Expression is used to create an anonymous function which is the same with C#.

Below C# and Java code are equivalent.

class App
{
    public static void Main(string[] args)
    {
        Action action = () => { Console.WriteLine("Printing from App class"); };
        action();
    }
}
@FunctionalInterface
interface Drawable {
    void Draw();
}

public class App {
    public static void main(String[] args) throws Exception {
        Drawable drawable = ()->System.out.println("Printing from App class");
        drawable.Draw();
    }
}

It is noticeable that C# code is less verbose than Java but that because Java naturally doesn’t have delegate type.