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

Note

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

  • List of parameters
  • The Arrow: Arrow separates the parameter from the body.
  • Body of the lambda
(String s) -> s.length()
  • Take one parameter string and return (implicit) an int value.
(Phone p) -> p.getPrice() > 100000
  • Take one parameter phone and return true if the price of the phone is greater than 1L
(int arg1, int arg2) -> {    System.out.println("I am printing arg1 : " + arg1);
}
  • Take two parameters and return nothing.
(parameters) -> expression
(parameters) -> {statements;}

Functional Interface

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");
  • Predicate: Transform an object in a boolean value, especially used for conditions
  • 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
Ajay Yadav

Ajay Yadav

Believer of Distributed Systems