Class LambdaExamples

java.lang.Object
net.jrodolfo.java_evolution.java08.LambdaExamples

public class LambdaExamples extends Object
Demonstrates lambda expressions, one of the main language features introduced in Java 8.

Before Java 8, passing behavior into a method usually meant creating an anonymous class. That made common operations such as filtering, sorting, and callbacks much more verbose than the actual idea being expressed.

Lambdas solve this by letting Java treat a small block of behavior as a value, as long as the target type is a functional interface. They are commonly used with interfaces such as Predicate, Comparator, and the interfaces in java.util.function. This also made the Stream API practical because stream operations can receive behavior directly.

  • Constructor Details

    • LambdaExamples

      public LambdaExamples()
  • Method Details

    • namesWithAtLeastFourLetters

      public List<String> namesWithAtLeastFourLetters(List<String> names)
      Filters a list by assigning a lambda expression to a Predicate.
      Parameters:
      names - the names to inspect
      Returns:
      only the names that contain at least four letters
    • sortByLength

      public List<String> sortByLength(List<String> names)
      Sorts names using a lambda expression as a Comparator.
      Parameters:
      names - the names to sort
      Returns:
      a new list sorted from shortest name to longest name
    • calculate

      public int calculate(int left, int right, LambdaExamples.IntegerOperation operation)
      Receives a custom operation as a method argument.
      Parameters:
      left - the left number used by the operation
      right - the right number used by the operation
      operation - the behavior to apply to both numbers
      Returns:
      the result produced by the operation
    • normalizedPositiveDifference

      public int normalizedPositiveDifference(int left, int right)
      Uses a multi-statement lambda body.

      Single-expression lambdas can omit braces and return. When the lambda needs more than one statement, Java requires a block body and an explicit return for non-void functional interfaces.

      Parameters:
      left - the left number used by the operation
      right - the right number used by the operation
      Returns:
      a normalized score
    • sortWithAnonymousClass

      public List<String> sortWithAnonymousClass(List<String> names)
      Sorts names with an anonymous class, the older style commonly used before Java 8 lambdas.
      Parameters:
      names - the names to sort
      Returns:
      a new list sorted alphabetically
    • sortWithLambda

      public List<String> sortWithLambda(List<String> names)
      Sorts names with a lambda expression, showing the shorter Java 8 replacement for a simple anonymous class.
      Parameters:
      names - the names to sort
      Returns:
      a new list sorted alphabetically