Last active
March 13, 2022 16:23
-
-
Save edjeordjian/be3f2795d4d59204f68e29d1f9c4769b to your computer and use it in GitHub Desktop.
Easy and simple example of lambda functions in Java.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* A lambda function (or expression) is a 'portable' anonymous function, which | |
* can be assigned to a variable. In Java, they are available since JDK 8. | |
*/ | |
public class LambdaTest { | |
public static void main(String[] args) { | |
/* The lambda function itself is the expression after the equals sign. | |
* | |
* The return type of the lambda corresponds to the return type of the | |
* abstract method in the functional interface, while the value in | |
* brackets (parameter) corresponds to the argument of the | |
* aforementioned method. | |
* | |
* The name "x" for the parameter is arbitrary, just like the | |
* content in curly braces, and has been chosen for briefness. | |
*/ | |
MyFunctionalInterface myLambda = (int x) -> { return x + 0.1; }; | |
System.out.println( myLambda.changeMyInt(1) ); | |
/* Although simple, this is not an example of an useful application for | |
* lambda functions. | |
* | |
* In Java, lambdas can be used to polymorphically check | |
* a condition across many objects by being passed as an | |
* argument to a function that checks the condition that must be met. | |
* That is the classical example that can be seen online, | |
* for example, in the official Java documentation: | |
* docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html | |
*/ | |
} | |
} | |
/* A lambda function needs an interface for being used. More precisely, it | |
* needs a 'functional' interface, which only has one abstract method, | |
* although it can have an arbitrary number of default methods. In lay | |
* terms, that method defines the 'kind' of lambda which will be usign | |
* (or 'consuming') the interface. | |
* | |
* If the functional interface has a boolean return type, the built-in | |
* interface Predicate<> from java.util.function can be used to avoid | |
* createing additional boolean interfaces | |
*/ | |
@FunctionalInterface | |
interface MyFunctionalInterface { | |
public abstract double changeMyInt(int myParameter); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment