Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learning Java Lambdas

You're reading from   Learning Java Lambdas An in-depth look at one of the most important features of modern Java

Arrow left icon
Product type Paperback
Published in Mar 2017
Publisher
ISBN-13 9781787282087
Length 114 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Toby Weston Toby Weston
Author Profile Icon Toby Weston
Toby Weston
Arrow right icon
View More author details
Toc

λ 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...

You have been reading a chapter from
Learning Java Lambdas
Published in: Mar 2017
Publisher:
ISBN-13: 9781787282087
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image