1f = lambda parameter : exp1 if cond else exp2
2
3# example
4f = lambda x: "even" if x%2==0 else "odd"
1A lambda expression is a short block
2of code which takes in parameters
3and returns a value. Lambda expressions
4are similar to methods, but they do
5not need a name and they can be
6implemented right in the body of a method.
7
8parameter -> expression
9
10To use more than one parameter, wrap them in parentheses:
11
12(parameter1, parameter2) -> expression
13
14Example
15Use a lamba expression in the ArrayList's
16forEach() method to print every item in the list:
17
18import java.util.ArrayList;
19
20public class Main {
21 public static void main(String[] args) {
22 ArrayList<Integer> numbers = new ArrayList<Integer>();
23 numbers.add(5);
24 numbers.add(9);
25 numbers.add(8);
26 numbers.add(1);
27 numbers.forEach( (n) -> { System.out.println(n); } );
28 }
1// C++ program to demonstrate lambda expression in C++
2#include <bits/stdc++.h>
3using namespace std;
4
5// Function to print vector
6void printVector(vector<int> v)
7{
8 // lambda expression to print vector
9 for_each(v.begin(), v.end(), [](int i)
10 {
11 std::cout << i << " ";
12 });
13 cout << endl;
14}
15
16int main()
17{
18 vector<int> v {4, 1, 3, 5, 2, 3, 1, 7};
19
20 printVector(v);
21
22 // below snippet find first number greater than 4
23 // find_if searches for an element for which
24 // function(third argument) returns true
25 vector<int>:: iterator p = find_if(v.begin(), v.end(), [](int i)
26 {
27 return i > 4;
28 });
29 cout << "First number greater than 4 is : " << *p << endl;
30
31
32 // function to sort vector, lambda expression is for sorting in
33 // non-decreasing order Compiler can make out return type as
34 // bool, but shown here just for explanation
35 sort(v.begin(), v.end(), [](const int& a, const int& b) -> bool
36 {
37 return a > b;
38 });
39
40 printVector(v);
41
42 // function to count numbers greater than or equal to 5
43 int count_5 = count_if(v.begin(), v.end(), [](int a)
44 {
45 return (a >= 5);
46 });
47 cout << "The number of elements greater than or equal to 5 is : "
48 << count_5 << endl;
49
50 // function for removing duplicate element (after sorting all
51 // duplicate comes together)
52 p = unique(v.begin(), v.end(), [](int a, int b)
53 {
54 return a == b;
55 });
56
57 // resizing vector to make size equal to total different number
58 v.resize(distance(v.begin(), p));
59 printVector(v);
60
61 // accumulate function accumulate the container on the basis of
62 // function provided as third argument
63 int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
64 int f = accumulate(arr, arr + 10, 1, [](int i, int j)
65 {
66 return i * j;
67 });
68
69 cout << "Factorial of 10 is : " << f << endl;
70
71 // We can also access function by storing this into variable
72 auto square = [](int i)
73 {
74 return i * i;
75 };
76
77 cout << "Square of 5 is : " << square(5) << endl;
78}