Lambda Expressions in Java Examples

Lambda expressions in Java provide a clear and concise way to implement functional interfaces—interfaces with just a single abstract method. Introduced in Java 8, lambda expressions streamline the writing of anonymous classes and are especially useful in functional programming concepts like map-reduce transformations on collections.

Syntax of Lambda Expressions

The basic syntax of a lambda expression is:

or for single-expression lambdas:

Example 1: Using Lambda with Runnable

Without lambda:

With lambda:

Example 2: Iterating Over a List

Using lambda expressions with the forEach method in List.

Example 3: Using Lambda with Comparator

Sorting a list of custom objects by a property.

Given a class Person:

Sorting by age:

Example 4: Using Lambda with Stream API

Filtering and mapping with Streams:

This filters the people list to only those older than 23 and then maps to their names, printing each name.

Example 5: Using Lambda to Implement Functional Interfaces

Using a custom functional interface:

These examples with lambda expressions in Java demonstrate their utility in creating more readable and concise code, especially when working with collections, threads, and implementing functional interfaces. The expected outputs are included as comments to help verify the results of each code snippet when executed.

Conclusion

Lambda expressions in Java enhance the expressiveness and conciseness of your code, making it easier to work with functionalities that can be represented as single-method interfaces. They are particularly powerful in combination with the Stream API for processing collections and can significantly reduce the verbosity of your Java code.

Leave a Reply

Your email address will not be published. Required fields are marked *