Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learning Java Lambdas

You're reading from  Learning Java Lambdas

Product type Book
Published in Mar 2017
Publisher
ISBN-13 9781787282087
Pages 114 pages
Edition 1st Edition
Languages
Author (1):
Toby Weston Toby Weston
Profile icon Toby Weston
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 we were to...

lock icon The rest of the chapter is locked
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 €14.99/month. Cancel anytime