Lambda In Java

  1. Understanding Lambda Expressions and its syntax.
  2. Built-in functional interfaces.

Understanding Lambda Expressions and its syntax

public void testDrive(List<Car> cars, String modelToTest) {        
for (Car car : cars) {
if (car.model.equals(modelToTest)) {
car.drive();
}
}
}
  • I defined our CarTester function interface where we provided one abstract method that accepts the Car object and returns a boolean.
  • Added CarTester as an argument to testDrive method and using needToTest method of CarTester to see what car needs to be tested.
  • Using lambda syntax in the main method to define on which car object to run the drive method.
// test Tesla and Audi models
testDrive.testDrive(cars, (Car e) -> {
return e.model.equals("Tesla") || e.model.equals("Audi");
});
// test white cars only
testDrive.testDrive(cars, (Car e) -> {
return e.color.equals("white");
});
// test all white cars
testDrive.testDrive(cars, e -> e.color.equals("white"));

Built-in functional interfaces

common functional interfaces
  • I removed my own interface and just used Predicate
  • The rest of the code is the same and it works as expected.

--

--

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