Lambda in Java

Comparator<Phone> comparator = new Comparator<Phone>() {
@Override
public int compare(Phone ph1, Phone ph2) {
return ph1.getPrice().compareTo(ph2.getPrice());
}
};
Collections.sort(phones, comparator);

Lambda Expression

Lambda expression is a succinct illustration of an anonymous function.

Note

Technically lambda is not allowing you to do anything new that you can’t do before java 8. But using lambda, you don’t need to write anonymous classes to utilize the behavior parameterization.

Comparator<Phone> comparator = new Comparator<Phone>() {
@Override
public int compare(Phone ph1, Phone ph2) {
return ph1.getPrice().compareTo(ph2.getPrice());
}
};
Comparator<Phone> phoneComparator = (Phone p1, Phone p2) -> p1.getPrice().compareTo(p2.getPrice());

Components of Lambda

  • The Arrow: Arrow separates the parameter from the body.
  • Body of the lambda
(String s) -> s.length()
(Phone p) -> p.getPrice() > 100000
(int arg1, int arg2) -> {    System.out.println("I am printing arg1 : " + arg1);
}
(parameters) -> expression
(parameters) -> {statements;}

Functional Interface

The interface defines precisely one abstract method.

public interface PhonePredicate {
boolean test(Phone phone);
}
Runnable r = new Runnable() {
public void run() {
System.out.println("Hello World Runnable");
}
};
Runnable r = () -> System.out.println("Hello World Runnable");
  • Consumer: Consume an object and returns nothing.
  • Function: Transform one object to another.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store