Few more examples of lambda expression

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.kb.Lambda;
 
public class LambdaEx1 {
    public static void main(String[] args) {
        Runnable r = new Runnable() {
            
            @Override
            public void run() {
                System.out.println("old way of calling run method");
                
            }
        };
        
        r.run();
        Runnable newR = () -> System.out.println("new way of calling run method using Lambda");
        newR.run();
    }
 
}
package com.kb.Lambda;

public class LambdaEx1 {
	public static void main(String[] args) {
		Runnable r = new Runnable() {
			
			@Override
			public void run() {
				System.out.println("old way of calling run method");
				
			}
		};
		
		r.run();
		Runnable newR = () -> System.out.println("new way of calling run method using Lambda");
		newR.run();
	}

}

Output

1
2
3
new Thread(
    () -> System.out.println("run method")
).start();
new Thread(
    () -> System.out.println("run method")
).start();

So in above code, compiler automatically detects that lambda expression can be casted to Runnable interface from Thread class’s constructor signature public Thread(Runnable r) { }.

Example for Functional interface with lambda on method call

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.kb.Lambda;
 
@FunctionalInterface
interface FunctionalInterfaceExample1{
    void show();
}
 
public class FunctionalInterfaceAndLambda {
    
    static void executeFunctionalInterface(FunctionalInterfaceExample1 example1){
        example1.show();
    }
 
    
    public static void main(String[] args) {
        
        //old way1
        executeFunctionalInterface(new FunctionalInterfaceExample1() {
            
            @Override
            public void show() {
                System.out.println("old way of defining anonymous inner class");
                
            }
        });
        
           // old way2
        FunctionalInterfaceExample1 ex1 = new FunctionalInterfaceExample1() {
            
            @Override
            public void show() {
                System.out.println("still old way of defining anonymous inner class");
                
            }
        };
        
        executeFunctionalInterface(ex1);
        
        
        //new way using lambda
        
        executeFunctionalInterface(() -> {System.out.println("new way of defining anonymous inner class using lambda");});
        
    }
 
}
package com.kb.Lambda;

@FunctionalInterface
interface FunctionalInterfaceExample1{
	void show();
}

public class FunctionalInterfaceAndLambda {
	
	static void executeFunctionalInterface(FunctionalInterfaceExample1 example1){
		example1.show();
	}

	
	public static void main(String[] args) {
		
		//old way1
		executeFunctionalInterface(new FunctionalInterfaceExample1() {
			
			@Override
			public void show() {
				System.out.println("old way of defining anonymous inner class");
				
			}
		});
		
           // old way2
		FunctionalInterfaceExample1 ex1 = new FunctionalInterfaceExample1() {
			
			@Override
			public void show() {
				System.out.println("still old way of defining anonymous inner class");
				
			}
		};
		
		executeFunctionalInterface(ex1);
		
		
		//new way using lambda
		
		executeFunctionalInterface(() -> {System.out.println("new way of defining anonymous inner class using lambda");});
		
	}

}

Output

Collection iteration with lambda
forEach method is added to List interface in Java8 and it can be used as below with lambda.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.kb.Lambda;
 
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
 
public class IteratingList {
 
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        list.add(10);
        list.add(20);
        
        //old way of iterating
        for (Integer element : list) {
            System.out.println(element);
        }
 
        System.out.println("-----------------");
 
        //new way using lambda
        list.forEach(element -> {System.out.println(element);});
 
    }
 
}
package com.kb.Lambda;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class IteratingList {

	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>();
		list.add(10);
		list.add(20);
		
		//old way of iterating
		for (Integer element : list) {
			System.out.println(element);
		}

		System.out.println("-----------------");

		//new way using lambda
		list.forEach(element -> {System.out.println(element);});

	}

}

Output

10
20
—————–
10
20

Calculator example of lambda expression

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.kb.Lambda;
 
public class Calculator {
      
    interface IntegerMath {
        int operation(int a, int b);   
    }
  
    public int operateBinary(int a, int b, IntegerMath operation) {
        return operation.operation(a, b);
    }
 
    public static void main(String... args) {
    
        Calculator myApp = new Calculator();
        IntegerMath addition = (a, b) -> a + b;
        IntegerMath subtraction = (a, b) -> a - b;
        System.out.println("40 + 2 = " +
            myApp.operateBinary(40, 2, addition));
        System.out.println("20 - 10 = " +
            myApp.operateBinary(20, 10, subtraction));    
    }
}
package com.kb.Lambda;

public class Calculator {
	  
    interface IntegerMath {
        int operation(int a, int b);   
    }
  
    public int operateBinary(int a, int b, IntegerMath operation) {
        return operation.operation(a, b);
    }
 
    public static void main(String... args) {
    
        Calculator myApp = new Calculator();
        IntegerMath addition = (a, b) -> a + b;
        IntegerMath subtraction = (a, b) -> a - b;
        System.out.println("40 + 2 = " +
            myApp.operateBinary(40, 2, addition));
        System.out.println("20 - 10 = " +
            myApp.operateBinary(20, 10, subtraction));    
    }
}

Output is

Comparator with lambda expression

Create a class person

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.kb.Lambda;
 
public class Person {
    
    String name;
    String designation;
    int age;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDesignation() {
        return designation;
    }
    public void setDesignation(String designation) {
        this.designation = designation;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    @Override
    public String toString() {
        return "name is "+name+" age is "+age+" designation is "+designation;
    }
 
}
package com.kb.Lambda;

public class Person {
	
	String name;
	String designation;
	int age;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDesignation() {
		return designation;
	}
	public void setDesignation(String designation) {
		this.designation = designation;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "name is "+name+" age is "+age+" designation is "+designation;
	}

}

Create a client class which uses person

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.kb.Lambda;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
 
public class PersonUser {
 
    public static void main(String[] args) {
        Person p1 = new Person();
        p1.setName("kb");
        p1.setDesignation("se");
        p1.setAge(26);
        
        Person p2 = new Person();
        p2.setName("hani");
        p2.setDesignation("se");
        p2.setAge(28);
        
        List<Person> people = new ArrayList<Person>();
        people.add(p1);
        people.add(p2);
        System.out.println("people before sorting");
        System.out.println(people);
        //Collections.sort(people,new PersonComparator());
        Collections.sort(people,new Comparator<Person>() {
            @Override
            public int compare(Person p1, Person p2) {
                return p1.getName().compareTo(p2.getName()) ;
            }
            
        });
        System.out.println("people after sorting");
        System.out.println(people);
    }
}
package com.kb.Lambda;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class PersonUser {

	public static void main(String[] args) {
		Person p1 = new Person();
		p1.setName("kb");
		p1.setDesignation("se");
		p1.setAge(26);
		
		Person p2 = new Person();
		p2.setName("hani");
		p2.setDesignation("se");
		p2.setAge(28);
		
		List<Person> people = new ArrayList<Person>();
		people.add(p1);
		people.add(p2);
		System.out.println("people before sorting");
		System.out.println(people);
		//Collections.sort(people,new PersonComparator());
		Collections.sort(people,new Comparator<Person>() {
			@Override
			public int compare(Person p1, Person p2) {
				return p1.getName().compareTo(p2.getName()) ;
			}
			
		});
		System.out.println("people after sorting");
		System.out.println(people);
	}
}

Look at the code

1
2
3
4
5
6
7
 Collections.sort(people,new Comparator<Person>() {
            @Override
            public int compare(Person p1, Person p2) {
                return p1.getName().compareTo(p2.getName()) ;
            }
            
        });
 Collections.sort(people,new Comparator<Person>() {
			@Override
			public int compare(Person p1, Person p2) {
				return p1.getName().compareTo(p2.getName()) ;
			}
			
		});

which takes comparator type as a parameter and provides implementation to the compareTo() method.
Now above code can be replaced using lambda expression as below

1
Collections.sort(people, (a,b) ->{ return a.getName().compareTo(b.getName());});
Collections.sort(people, (a,b) ->{ return a.getName().compareTo(b.getName());});

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on