Lambdas in Java: what are they, and why are they useful?

Lambda expressions or lambdas are functions that can be used as though they were ordinary variables or expressions. Using a lambda expression in Java, we can refer to a piece of code almost as easily as we can refer to an ordinary object or value. This allows us to:

There are a variety of cases where lambdas are useful. Example uses of lambdas include:

All of the above couold be done without lambdas, using existing Java language features such as interfaces or anonymous classes. Prior to the introduction of lambdas in Java 8, all of the above could be achieved, and indeed, were achieved in the relevant standard Java APIs. But having to create an anonymous class just to pass a piece of code from one method to another meant that functions or blocks of code were not "first-class citizens" of the language: you could not assign them to variables, pass them into methods or declare them in the first place as straightforwardly as a numeric type or object reference. From Java 8 onwards, lambdas provide a more efficient solution, both in terms of the code that needs to be written and in terms of the resulting implementation and performance. As we will see, many of the Java APIs have been updated to allow lambdas to be used as comparators, callbacks and the other typical uses that we have just described.

Getting started with lambdas

On the next page, we provide a more detailed introduction to lambdas in Java.

Subsequent pages will look at various associated topics including:

If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.