Examples of Lambda Expression


FUNCTIONAL PROGRAMMINGOOP
Does not exist StateExists State
Uses Immutable dataUses Mutable data
It follows Declarative Programming ModelIt follows Imperative Programming Model
Stateless Programming ModelStateful Programming Model
Main Fcous on: “What you are doing”Main focus on “How you are doing”
Good for Parallel (Concurrency) ProgrammingPoor for Parallel (Concurrency) Programming
Good for BigData processing and analysisNOT Good for BigData processing and analysis
Supports pure EncaspulationIt breaks Encaspulation concept
Functions with No-Side EffectsMethods with Side Effects
Functions are first-class citizensObjects are first-class citizens
Primary Manipulation Unit is “Function”Primary Manipulation Unit is Objects(Instances of Classes)
Flow Controls: Function calls, Function Calls with RecursionFlow Controls: Loops, Conditional Statements
It uses “Recursion” concept to iterate Collection Data.It uses “Loop” concept to iterate Collection Data. For example:-For-each loop in Java
Order of execution is less importance.Order of execution is must and very important.
Supports both “Abstraction over Data” and “Abstraction over Behavior”.Supports only “Abstraction over Data”.
We use FP when we have few Things with more operations.We use OOP when we have few Operations with more Things. For example: Things are classes and Operations are Methods in Java.

Following are some examples of Lambda expressions.


(arg1, arg2...) -> { body }

(type1 arg1, type2 arg2...) -> { body } 
 
 
 
(int a, int b) -> {  return a + b; }

() -> System.out.println("Hello World");

(String s) -> { System.out.println(s); }

() -> 42

() -> { return 3.1415 }; 
 
 
 
Syntax of Lambda Expression:

The syntax of a lambda expression consists of the following:
  1. A comma-separated list of formal parameters enclosed in parentheses. In this case, it is (Dog m, Dog n)
  2. The arrow token ->
  3. A body, which consists of a single expression or a statement block. In this case, it is one single expression - Integer.compare(m.getWeight(), n.getWeight())
 
 
 
 

Examples of Lambda Expression


1.

//Old way:

If you want to add a buttonclicklistener on android or in any button click use cases you can use this code, in a new way:

 

button.addActionListener(new ActionListener() {
 @Override
 public void actionPerformed(ActionEvent e) {
  System.out.println("The button was clicked using old fashion code!");
 }
});



//New Way:


button.addActionListener( (e) -> {
  System.out.println("The button was clicked. From lambda expressions !");
});
 
 
 

2.

//Old way:


List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
for(Integer n: list) {
 System.out.println(n);
}



//New Way:


List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
list.forEach(n -> System.out.println(n));


//or we can use :: double colon operator in Java 8
list.forEach(System.out::println); 
 
 
3.
 
 
 
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Main {
  
 public static void main(String [] a)  {

  List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);

  System.out.println("Print all numbers:");
  evaluate(list, (n)->true);

  System.out.println("Print no numbers:");
  evaluate(list, (n)->false);

  System.out.println("Print even numbers:");
  evaluate(list, (n)-> n%2 == 0 );

  System.out.println("Print odd numbers:");
  evaluate(list, (n)-> n%2 == 1 );

  System.out.println("Print numbers greater than 5:");
  evaluate(list, (n)-> n > 5 );

 }

 public static void evaluate(List<Integer> list, Predicate<Integer> predicate) {
  for(Integer n: list)  {
   if(predicate.test(n)) {
    System.out.println(n + " ");
   }
  }
 }

} 
 
 
 
 
4.
 
 

//Old way:


List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
for(Integer n : list) {
 int x = n * n;
 System.out.println(x);
}



//New Way:


List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
list.stream().map((x) -> x*x).forEach(System.out::println); 
 
 
 
 
 
5.
 
 

//Old way:


List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
int sum = 0;
for(Integer n : list) {
 int x = n * n;
 sum = sum + x;
}
System.out.println(sum);


//New Way:


List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
int sum = list.stream().map(x -> x*x).reduce((x,y) -> x + y).get();
System.out.println(sum); 
 
 
 
6.
 

//Old way:


new Thread(new Runnable() {
 @Override
 public void run() {
  System.out.println("Hello from thread");
 }
}).start();

//New Way:


new Thread(
 () -> System.out.println("Hello from thread")
).start();

    
 
  7. 


If you have an array and repeatedly you have to use them in a method with different approaches, it can be done in a more generic and reusable way :

public class Main {
public static int sumAll(List<Integer> numbers, Predicate<Integer> p) {
    int total = 0;
    for (int number : numbers) {
        if (p.test(number)) {
            total += number;
        }
    }
    return total;
}
    public static void main(String[] args) {
       
        List<Integer> numbers= Arrays.asList(1,2,3,4,5,6);
        System.out.println(sumAll(numbers, n -> true));
        System.out.println(sumAll(numbers, n -> n % 2 == 0));
        System.out.println(sumAll(numbers, n -> n > 3));
    }
}


 


 

 

 

Comments

Popular posts from this blog

DIfferent issues that may occur in Apache spark and their remedies.

Parquet is a column based data store or File Format (Useful for Spark read/write and SQL in order to boost performance)

Steps to Install zeppelin with spark