My first Java 8 Lambda Expression

My first Java Lambda Expression

Keeping up with the pace of a blog post a week I have wanted to take a closer look at Java 8 developer preview ever since it was release mid-November. Originally due to be in Java 7 but was dropped as part of the “Plan B” effort to help ship Java 7 earlier. Java 7 has now shipped and the focus is on the Java 8 which is due to be release late 2012. The syntax was finally confirmed after much debate by Brian Goetz on the lambda-dev mailing list and will adopt the C# syntax.  For more information on Lambda expressions in Java 8 check out the JSR-335

Wait, let’s start at the start. What are lambda expressions and why oh why do we need them so badly that people fall out over the syntax.

What is a lambda expression?

Put simply a lambda expression is

   Lambda is an operator used to denote anonymous functions

I just robbed that from Wikipedia, I surely can do better. In my words a lambda expression is

   A succinct way to represent an anonymous method

My worst attempt at defining lambda expression was

   Anonymous classes, but much cooler!!!

Many languages already support lambda expressions; I just noticed the Visual Basic has had support for a while now. To see our first lambda expression in action we are going to use Erlang as language of choice. I choose Erlang as I think its syntax is probably the cleanest around and can be understood by almost any developer.

F = fun(X) ->  X * X end,

Easy peasy? Now time to confuse you all again here is a Haskell example

numLongChains :: Int  
numLongChains = length (filter (\xs -> length xs > 15) (map chain [1..100]))

If you feel modern life as a programmer is too easy and feel you want to re-write your java web application in Haskell then you should continue reading Learn You a Haskell where the above example is borrowed. I love their explanation of the lambda syntax

“Lambdas are basically anonymous functions that are used because we need some functions only once. Normally, we make a lambda with the sole purpose of passing it to a higher-order function. To make a lambda, we write a \ (because it kind of looks like the greek letter lambda if you squint hard enough) and then we write the parameters, separated by spaces. After that comes a -> and then the function body. We usually surround them by parentheses, because otherwise they extend all the way to the right.”

C#, but I only like Java

I heard an expression recently “The determined Real Programmer can write fortran programs in any language” which brings me nicely to writing our first lambda expression in C#

Since the Java syntax is based on the C# syntax it is probably a good idea to visit the extraordinary world so few Java developers venture, .net land. In general, the syntax is

(Input Parameters) => Expression

This equates to

x => x + 1

Sometimes it is impossible for the compiler to infer the input type so you have to help it out by specifying the input types as follows

(int x, string s) => s.Length > x

These are technically Expression Lambdas, a Statement Lambdas is very similar but with braces

delegate void TestDelegate(string s);
TestDelegate myDel = n => { string s = n + " " + "World"; Console.WriteLine(s); };

Java Syntax,  Java Syntax,  Java Syntax

There has been a lot of debate on the exact specification of Java’s lambda expression syntax and I am sure it’s not over. Brian Gotez outlined the thoughts behind the decision in his email

Despite extensive searching, there was no clear winner among the alternatives (each form had some good aspects and some really not very good aspects, and there was no form that was clearly better than the others). So, we felt that it was better to choose something that has already been shown to work well in the two languages that are most like Java – C# and Scala – rather than to invent something new.

He defined the C# syntax as

lambda = ArgList Arrow Body
ArgList = Identifier
             | "(" Identifier [ "," Identifier ]* ")"
             | "(" Type Identifier [ "," Type Identifier ]* ")"
Body = Expression
             | "{" [ Statement ";" ]+ "}"

And illustrated the definition with the following examples

x => x + 1
(x) => x + 1
(int x) => x + 1
(int x, int y) => x + y
(x, y) => x + y
(x, y) => { System.out.printf("%d + %d = %d%n", x, y, x+y); }
() => { System.out.println("I am a Runnable"); }

My First Java 8 Lambda

It’s getting late, I have downloaded the Java 8 JDK preview, written three pages of fluff on Lambda expressions but have yet to write one. So here goes, you can download Java 8 from Oracle at

I had a brief look but no IDE or early beta version of an IDE supports Java 8’s Lambda Expressions so I will have to code this one on the command line. My first working lambda expression in Java 8 is a small illustration

public class FirstLambda {

    enum SoccerResult{
        WON, LOST, DRAW

    interface SoccerService {
        SoccerResult getSoccerResult(Integer teamA, Integer teamB);

    public void soccerResultPredictor() {

        SoccerService soccerService = (teamA, teamB) -> {
            SoccerResult result = null;
            if (teamA == teamB){
                result = SoccerResult.DRAW;
            }else if(teamA < teamB){
                result = SoccerResult.LOST;
                result = SoccerResult.WON;
            return result;

        // man utd vs wolves
        SoccerResult soccerResult = soccerService.getSoccerResult(3,1);
        System.out.println("soccerResult = " + soccerResult);


    public static void main(String... args) {
        FirstLambda firstLambda= new FirstLambda();


In this simple example we create a lambda expression to work out the result of the team a’s match. The lambda expression itself is represented by

        SoccerService soccerService = (teamA, teamB) -> {
            SoccerResult result = null;
            if (teamA == teamB){
                result = SoccerResult.DRAW;
            }else if(teamA < teamB){
                result = SoccerResult.LOST;
                result = SoccerResult.WON;
            return result;


I have barely scratched the surface of Lamdba Expressions in this post but as the spec matures and tooling support improves I hope to start to learn more about the more complicated inner working of this language feature.


I really recommend you to rea Brian’s Goetz’s update on the lambda syntax in java! I wish I had this over the weekend

About these ads

10 thoughts on “My first Java 8 Lambda Expression

  1. Very cool to see Java scoring lambdas – and equally nice to see a dev venture into .NET land :D Great post. Speaking of .NET land, I’m venturing into Java land, can you recommend a good book to come up to speed on Java as well as one for the JVM?

  2. Though i had an idea of what lambda was, ur post helped to put some clarity. Hoping to read more on this. BTW, why not Basel vs Manchester United????

  3. Pingback: Blog: My first Java 8 Lambda Expression | Oracle | Syngu
  4. Looks nice.
    Although I like more the C++ way of doing it.
    [access to variables] (type variable1…) { } -> and you can indicate a specific return type;
    [] () -> double { };
    [] () {};
    Offers more ways/possibilities of using it. Anyway, nice implementation. Usable. I was writing an application now using Java 7 and wanted to use Lambda, wondered to this blog…

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s