Java 8 Features with Examples

Lambda Expression:

Its a concise representation of an anonymous function that can be passed around, it has below mentioned properties.

  1. Anonymous : It does not have a explicit name like a method
  2. Function: We call it as a function because its not associated with a class like a method is
  3. Passed Around: A lambda expression can be passed as an argument or stored in a variable
  4. Concise – We don’t need to write lot of boilerplate code like we do for anonymous classes
Before:

Comparator<Employee> byId = new Comparator<Employee>() {
public int compare(Employee e1, Employee e2){
return e1.getId().compareTo(e2.getId());
}
};

After: 

Comparator<Employee> byId = (Employee e1,Employee e2)-> e1.getId().compareTo(e2.getId());

Use cases of Lambda, where lambda can be used

1. In Boolean Expression : (List<String> list)-> list.isEmpty()
2. Create new Objects:     ()-> new Employee(12)
3. Consuming from an object : (Employee e) -> {System.out.println(e.getId());}
4. Selecting from an object : (String s)->s.length()
5. Combining 2 values: (int a ,int b)->a+b
6. Comparing 2 objects: (Employee e1,Employee e2)->e1.getId().compareTo(e2.getId())

Lambda Expression are used with Functional Interfaces

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *