Book Image

Learning Java Lambdas

By : Toby Weston
Book Image

Learning Java Lambdas

By: Toby Weston

Overview of this book

In this short book, we take an in-depth look at lambdas in Java, and their supporting features. The book covers essential topics, such as functional interfaces and type inference, and the key differences between lambdas and closures. You will learn about the background to functional programming and lambdas, before moving on to understanding the basic syntax of lambdas and what differentiates these anonymous functions from standard anonymous classes. Lastly, you'll learn how to invoke lambdas and look at the bytecode generated. After reading this book, you'll understand lambdas in depth, their background, syntax, implementation details, and how and when to use them. You'll also have a clear knowledge of the difference between functions and classes, and why that's relevant to lambdas. This knowledge will enable you to appreciate the improvements to type inference that drive a lot of the new features in modern Java, and will increase your understanding of method references and scoping.
Table of Contents (10 chapters)

λ basic syntax


Let's take a look at the basic lambda syntax.

A lambda is basically an anonymous block of functionality. It's a lot like using an anonymous class instance. For example, if we want to sort an array in Java, we can use the Arrays.sort method which takes an instance of the Comparator interface.

It would look something like this:

Arrays.sort(numbers, new Comparator<Integer>() {
    @Override
    public int compare(Integer first, Integer second) {
        return first.compareTo(second);
    }
});

The Comparator instance here is a an abstract piece of the functionality; it means nothing on its own; it's only when it's used by the sort method that it has purpose.

Using Java's new syntax, you can replace this with a lambda which looks like this:

Arrays.sort(numbers, (first, second) -> first.compareTo(second));

It's a more succinct way of achieving the same thing. In fact, Java treats this as if it were an instance of the Comparator class. If we were to...