Java can haz Lambdas (C# does haz for 10 years)

Did you hear? Java 8 now has Lambda expressions!

My first reaction was this:

Lambda expressions are a compact way to represent functions inline as expressions. If you're a C# developer like me, you've already been using them for years. For example, with LINQ to Objects:

 

var numbers = new List<int>() {1, 5, 10, 12, 13, 17, 20, 22};
var evenNumbers = numbers.Where(m => m%2 == 0);

The .Where filter function isn't defined by List<T> itself by the way, it's an extension method defined by System.Linq.Enumerable. Look at its source code (yay, great move Microsoft!) and you'll see that its implementation contains no magic: it's simply iterating over the entire collection, returning elements for which the predicate is true (here).

Here's the same code snippet in Java 8:

 

List<integer> numbers = Arrays.asList(1, 5, 10, 12, 13, 17, 20, 22);
Stream<integer> evenNumbers = numbers.stream().filter(m -> m%2 == 0);

You'll notice a few small differences: Java still doesn't have implicit typing and won't allow you using the var keyword. So you will have to figure out the return type of an expression, the compiler won't do it for you. Also, you'll notice stream() - you can now filter, map, sort, basically do all the good stuff C# developers already know from LINQ to Objects. Not all of the operators are defined on the various collection classes directly though, but on Stream.

Some operators have been added directly to the collection classes though. For example, sort (which makes sense, you wouldn't wanna "sort" a stream):

 

numbers.sort((x, y) -> Integer.compare(x, y));

So, did .sort get added to the existing List<T>? Or did Java 8 also introduce extension methods like in .NET did, like, 10 years ago?

It's actually neither. Specifically to support Lamdas, Java 8 also introduces default methods, also known as defender methods or (confusingly, at least for .NET programmers) virtual extension methods. In a nutshell, default methods allow for providing a default method implementation on an interface (!). Yes, you read this right. An interface which contains implementation. While this sounds akward, it's sort of an elegant way to add functionality to existing interfaces like List without breaking everyone's existing code.

By the way, Eclipse annotates default methods for you:

default

Anyways. Welcome to 2014, dear Java developers! And fingers crossed, Android developers, this is about to make your life a lot easier as well in the near future.

Discuss on Hacker News.


Written on July 11, 2014.