Java Lambda And Function

wahyu eko hadi saputro
2 min readFeb 4, 2021

--

Starting from java 8, java has feature called lambda and the symbol of lamda is ->. In other programming language lambda also called closures, anonymous functions or blocks. Essentially lambda is a block of code that can be passed as an argument to a function call.

In java, lambda is not actually anonymous functions, because every function or method in java is encapsulated inside class. So java uses anonymous class as lambda implementation. And then what is anonymous class ? anonymous class is a class without name or unknown class name. Anonymous class is constructed by implementing interface or abstract method. Here is the example :

  1. Create interface for example : IAnonymous
interface IAnonymous{
void print();
}

2. Create Anonymous class

public class MainAnonymous {
public static void main(String[] args) {
// Create instance of Anonymous Class
IAnonymous anonymousClassIntance = new IAnonymous(){
@Override
public void print() {
// TODO Auto-generated method stub
System.out.println("Anonymous Class");
}
};
anonymousClassIntance.print();
}
}
Output :
Anonymous Class

Next we will discuss creating lambda by using anonymous class.

  1. Create Interface
@FunctionalInterface
public interface InterfaceLamda {
void print();
}

@FunctionalInterface based on java doc @FunctionalInterface is An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification. Conceptually, a functional interface has exactly one abstract method.

Basic requirement of interface for lamda or functional interface are :
a. Add @FunctionalInterface to interface declaration
b. The interface must only has on abstract method. void print() is abstract method.

2. Create lambda implementation

public class MainLambda {
public static void main(String[] args) {
// Create instance of Anonymous Class
InterfaceLamda interfaceLamdaInstance = new InterfaceLamda(){
@Override
public void print() {
// TODO Auto-generated method stub
System.out.println("Test Lambda");
}
};
interfaceLamdaInstance.print();

InterfaceLamda interfaceLamdaInstance1 = ()->{System.out.println("Test Lambda");};
interfaceLamdaInstance1.print();
}
}
Output:
Test Lambda
Test Lambda

Java lambda implementation on java package :

java collection : iterable interface

Comsumer Interface is a paramater for forEach function / method. Consumer is part of java.util.function that vary useful for creating lambda function.

References :

https://www.javatpoint.com/java-lambda-expressions
https://martinfowler.com/bliki/Lambda.html

--

--

No responses yet