Sobes.tech
Middle

What are lambda expressions in Java and what functionality do they provide?

sobes.tech AI

Answer from AI

Lambda expressions in Java (starting from version 8) are a concise way to represent anonymous functions.

They provide the following functionalities:

  • Implementation of functional interfaces: A lambda expression implements the single abstract method of a functional interface.
  • Parameterization of behavior: They allow passing behavior (logic) as arguments to methods.
  • Improved code readability: They replace anonymous inner classes for event listeners, comparators, etc., making the code more concise.
  • Integration with Stream API: The main way to work with data streams for filtering, transforming, and aggregating.

Example syntax:

// (parameters) -> { expression body }

// Without parameters:
Runnable runnable = () -> System.out.println("Hello Lambda!");

// With one parameter:
Consumer<String> greeter = name -> System.out.println("Hello, " + name);

// With multiple parameters:
BiFunction<Integer, Integer, Integer> adder = (a, b) -> a + b;

// With a block of code:
Comparator<String> lengthComparator = (str1, str2) -> {
    int len1 = str1.length();
    int len2 = str2.length();
    return Integer.compare(len1, len2);
};
What are lambda expressions in Java and what… - sobes.tech