Let’s discuss some more example of the lambda expression.
Example of Lambda expression with empty parameters
public interface Show { public void display(); }
public class ExampleWithoutParameters { public static void main(String[] args) { Show show = () -> { System.out.println("Not using any parameter"); System.out.println("Provoding body to display() method"); }; show.display(); } }
Output: Not using any parameter
Providing body to display() method
Example of Lambda expression with parameters
public interface Show { public void display(int a, int b); }
public class ExampleWithParameters { public static void main(String[] args) { Show show = (int a, int b) -> { System.out.println("Using two parameter value is:"+a+" "+b); System.out.println("Provoding body to display() method"); }; show.display(2,8); } }
Output: Using two parameter value is:2 8
Provoding body to display() method
Example of Lambda expression with forEach
import java.util.ArrayList; public class ExampleWithForEach { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("Hi"); list.add("Hello"); list.add("Hey"); list.add("Bye"); list.add("Bye!!!!!"); list.forEach(name -> System.out.println(name)); } }
Output: Hi
Hello
Hey
Bye
Bye!!!!!
Example with forEach for User-defined class
class Student { int rollNo; String className; String name; public Student(int rollNo, String className, String name) { this.rollNo = rollNo; this.className = className; this.name = name; } public int getRollNo() { return rollNo; } public void setRollNo(int rollNo) { this.rollNo = rollNo; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
import java.util.ArrayList; public class ExampleWithForEach { public static void main(String[] args) { ArrayList<Student> list = new ArrayList<Student>(); list.add(new Student(1, "MCA", "Ram")); list.add(new Student(2, "MSC", "Sham")); list.add(new Student(3, "BCA", "Krishan")); list.add(new Student(4, "CA", "Ravi")); list.add(new Student(5, "BBA", "Ram")); list.forEach(student -> System.out.println(student.getName())); } }
Output: Ram
Sham
Krishan
Ravi
Ram
Creating thread by using Lambda expression
class CreatingThreadByLambda { public static void main(String args[]) { System.out.println("Thread id of Main thread is = "+ Thread.currentThread().getId()); Runnable runnable = () -> { System.out.println("Thread is running..."); System.out.println("Thread id of new thread is="+Thread.currentThread().getId()); }; Thread thread = new Thread(runnable); thread.start(); } }
Output: Thread id of Main thread is = 1
Thread is running…
Thread id of new thread is=12