Use Java 8 Lambda Expressions

Java 8's Lambda expressions is the biggest change to the Java language. For the following reasons use Lambda expressions across your application.
This feature:

  • Enables you to treat functionality as a method argument.
  • Helps to easily express instances of single-method interfaces (functional interfaces).
  • You can replace anonymous class with a lambda expression.
  • Less code Ceremony.

Use Lambda when your application need to perform below use cases ...

  • Use Cases:

    • Filter on the Coupons by category and add for do redemption on the matching coupons.
    • Find all cars that match a specific search criteria (like make, model, year, milage).
    • Perform an action on all matching search cars. (like adding them to favorites).
    • Syntax:
      // (type1 argument1, type2 argument2 ... ) -> { statements }
      (int a, int b) ->  { System.out.print( a+b ); }
      () ->  { System.out.print( "Hello KickStartPros" ); }
      (String str1, String str2) ->  { return str1 + str2; }
      () -> 99
      () -> { return "Hello JAVA 8"}
      
    • Example Use Case:

      For rest of the section consider you are searching for Cars by combined (city and highway) mileage. Here Find and Print the cars whose mileage grater than a specified miles.

      public class Car {
        String make;
        String model;
        int combinedMileage;
        public Car(String make, String model, int combinedMileage) {
            // ...
        }
        public int getCombinedMileage() {
            return combinedMileage;
        }
        public void printCar() {
            // ...
        }
        // ...
      }
      
      public class CarServiceApplication {
      
        public static void main(String[] args) {
          searchCars(new ArrayList<Car>(Arrays.asList(new Car("Audi", "A1", 47)),
                                                      new Car("Toyota", "Sienna", 21)), 30);
        }
      
        public static void searchCars(List<Car> allCars, int combinedMileage) {
          for (Car c : allCars) {
              if (c.getCombinedMileage() >= combinedMileage) {
                  c.printCar();
              }
          }
        }
      }
      
  • Using Functional Interface Approach:

    Functional Interface is an interface where only one abstract method declared in it.
    Here CheckCar calss is the functional interface and check the highlighted code below.

    // Functional Interface - Only one abstract method.
    interface CheckCar {
        boolean test(Car c);
    }
    
    class CheckCarMileage implements CheckCar {
        int combinedMileage = 0;
        public CheckCarMileage (int combinedMileage ) {
           this.combinedMileage  = combinedMileage ;
        }
        public boolean test(Car c) {
            return c.getCombinedMileage() >= combinedMileage;
        }
    }
    
    public class CarServiceApplication {
    
      public static void main(String[] args) {
        searchCars(new ArrayList<Car>(Arrays.asList(new Car("Audi", "A1", 47)),
                                                    new Car("Toyota", "Sienna", 21)), 30);
      }
    
      public static void searchCars(List<Car> allCars, int combinedMileage) {
        printCars(allCars, new CheckCarMileage(combinedMileage));
      }
    
      public static void printCars(List<Car> allCars, CheckCar tester) {
        for (Car c : allCars) {
            if (tester.test(c)) {
                c.printCar();
            }
        }
      }
    }
    
  • Using Anonymous Class Approach:

    Instead of creating separate CheckCarMileage class, you can do the same filtering using Anonymous Class.
    interface CheckCar {
        boolean test(Car c);
    }
    
    public class CarServiceApplication {
      public static void main(String[] args) {
      searchCars(new ArrayList<Car>(Arrays.asList(new Car("Audi", "A1", 47)),
                                                    new Car("Toyota", "Sienna", 21)), 30);
      }
    
      public static void searchCars(List<Car> allCars, final int combinedMileage) {
        printCars(allCars,
        new CheckCar() { // Anonymous Class
         public boolean test(Car c) {
          return c.getCombinedMileage() >= combinedMileage;
         }
        });
      }
    
      public static void printCars(List<Car> allCars, CheckCar tester) {
        for (Car c : allCars) {
            if (tester.test(c)) {
                c.printCar();
            }
        }
      }
    }
    
  • Using Lambda Expression:

    In the above approach 'CheckCar' is a functional interface. To use lambda expression you can replace the anonymous class and use Standard Interface. Here Predicate class is standard functional interface for Criteria.
    //Standard Interface from Java API
    interface Predicate<T> {
        boolean test(T t);
    }
    
    public class CarServiceApplication {
      public static void main(String[] args) {
     searchCars(new ArrayList<Car>(Arrays.asList(new Car("Audi", "A1", 47)),
                                                    new Car("Toyota", "Sienna", 21)), 30);
      }
    
      public static void searchCars(List<Car> allCars, final int combinedMileage) {
         printCars(allCars,
          (Car c) -> { return c.getCombinedMileage() >= combinedMileage } ); // Lambda Expression
      }
    
      public static void printCars(List<Car> allCars, Predicate<Car> tester) {
        for (Car c : allCars) {
            if (tester.test(c)) {
                c.printCar();
            }
        }
      }
    }
    
  • Simplified Syntax:

    Check more simplified lambda expression in 'searchCars' method.
    • You can omit the parentheses if there is only one parameter.
    • No return statement or parathsis need if you specify a single expression. That expression will be evaluated and then returned.
    public class CarServiceApplication {
    // ...
      public static void searchCars(List<Car> allCars, final int combinedMileage) {
         printCars(allCars,
                   c -> c.getCombinedMileage() >= combinedMileage );// Simplified Lambda Expression
      }
    // ...
    }
    

No comments :

Post a Comment