Anonymous Functions in JAVA : Begineers

Reading Time: 4 minutes

In this blog we are going to learn what is anonymous function and types of anonymous function. So, now I am starting the anonymous functions in Java, one by one we are going to deep down to it and exploring every concept of it.

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 define as not bound to an identifier. Because,These are a form of nested function in allowing access to variables in the scope of the containing function (non-local functions).So,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.

Or,

An anonymous function (function literal, lambda abstraction abstraction, lambda function, lambda expressionor block) is function definition that is not bound to an identifier.Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function that needs to return a function.

Also, a lambda expression represents an anonymous function and 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 Parameters “);

  • One Parameter

(parameter) -> System.out.println(“One parameter is : ” + parameter);

or without parenthesis; parameter -> parameter (Identity function example)

  • Multiple parameters

(parameter1, parameter2) -> parameter1 + parameter2;

  • Parameter Types

(int a, String name) -> System.out.println(“id:” + a + ” name:” + name);

  • Code block

(parameter1, parameter2) -> { return parameter1 + parameter2; }

  • Nested lambda expression :Two nested expressions with the first one as closure
(id, defaultCost) -> {

  Optional<Product> product = productList.stream().filter(p -> p.getId() == id).findFirst();

  return product.map(p -> p.getCost()).orElse(defaultCost);

 }
  • As objects : The lambda expression is recommended to variable, lastly it is summoned by the interface strategy it carried out
public interface Comparator {
    public boolean compare (int x, int y);
 }

 Comparator myComparator = (x, y) -> return x > y;
 boolean result = myComparator.compare(5, 3);

So, we can relate it:

Arrays.sort ( customer_Array, new Comparator (<Customer>( ) {

    @Override
    public int compare ( Customer c1, Customer c2 ) {
        return c1.getAge ( ) - c2.getAge ( ) ;
    }
});

So, it becomes ->

Arrays.sort ( customer_Array, (c1,c2) -> c1.getAge( ) - c2.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 x, int y) ;

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

    public static void main (String[] args) {
        IntegerMath addition = (x, y) -> x + y;
        IntegerMath subtraction = (x, y) -> x - y;
        System.out.println("50 + 12= " + apply (50, 12, addition ));
        System.out.println("40 - 10 = " + apply (40, 10, subtraction ));
        System.out.println("30 - 15 = " + apply (30, 15, subtraction.swap( )));    
    }

Output of above :

 /usr/lib/jvm/java-1.11.0-openjdk-amd64/bin/java -javaagent:/snap/intellij-idea-community/

 50 + 12 =  62
 40 - 10  =  30
 30 - 15  = -15

 Process finished with exit code 0

So,here IntegerMath is a functional interface with default method swap and Lambda expressions that implement IntegerMath and passed to the apply ( ) method.

Closures :

These are the functions that evaluated in an environment containing bound variables and following example binds the variable “threshold” in an anonymous function that compares the input to the threshold.

def comp (threshold) :
    return lambda x: x < threshold

As a sort of generator of comparison functions we can use Closures :

>>> func_a  =  comp ( 10 )
>>> func_b  = comp ( 20 )

>>> print (func_a ( 5 ),  func_a ( 8 ),  func_a ( 13 ),  func_a ( 21 ) )
True   True   False   False

>>> print (func_b ( 5 ),  func_b ( 8 ),  func_b ( 13 ),  func_b ( 21 ) )
True   True   True   False 

It would be impractical to create a function for every possible comparison function and may be too inconvenient to keep the threshold around for further use.Regardless of the reason why a closure is used, the anonymous function is the entity that contains the functionality that does the comparing.

Currying :

Currying is the process of changing a function so that rather than taking multiple inputs and it takes a single input and returns a function which accepts the second input, and so forth. In addition a function that performs division any integer is transformed into one that performs division by a set integer.

>>>  def divide (x, y) :
          return x / y

>>>  def divisor (d) :
          return lambda x: divide (x, d)

>>>  half  = divisor ( 2 )
>>>  third = divisor ( 3 )

>>>  print ( half (22), third (41) )
        11.0    13.666666666666667

>>> print ( half ( 60 ), third ( 52 ) )
        30.0     17.333333333333334

It perhaps not common with currying when the use of anonymous functionsIt maybe not normal with currying when the utilization of mysterious functions.it still can be utilized.Therefore, in the above example, the function divisor generates functions with a specified divisor.Simillarly, The functions half and third curry the divide function with a fixed divisor.

The divisor function also forms a closure by binding the variable d.

Refrences

Thanks for reading this blog.Further, you can checkout our website knoldus.com for engineering solutions and you can find more awesome blogs at https://blog.knoldus.com

knoldus-advt-sticker

Written by 

He is a Software Intern at Knoldus Inc. He has done B.Tech from Dr. APJ Kalam Technical University Uttar-Pradesh. He is passionate about his work and having the knowledge of various programming languages like Java, C++, Python. But he is passionate about Java development and curious to learn Java Technologies. He is always impatient and enthusiastic to learn new things. He is good skills of Critical thinking and problem solving and always enjoy to help others. He likes to play outdoor games like Football, Volleyball, Hockey and Kabaddi. Apart from the technology he likes to read oldest granths originating in ancient India like Veda,Upanishad,Geeta etc.

Leave a Reply