Java8 Nuggets - Lambda Expressions

Overview

This is part I, in the series of “Java8 Nuggets” articles, that explicate how to introduce Java8 features in the codebase. This is mainly for me in case I need a quick reference in the future. So they are collected as listings from my personal notes taken from reading Oracle Java release blog.

Lambda Expression

Java 8 release has a number of different language improvements (apart from others) and Lambda syntax is a notable one.

  1. Lambda expressions
    printPersons(
        roster,
        new CheckPerson() {
            public boolean test(Person p) {
                return p.getGender() == Person.Sex.MALE
                    && p.getAge() >= 18
                    && p.getAge() <= 25;
            }
        }
    );
    
 
    
        printPersons(
            roster,
            (Person p) -> p.getGender() == Person.Sex.MALE
                && p.getAge() >= 18
                && p.getAge() <= 25
        );
    
 
  1. Method references
 
 Arrays.sort(rosterAsArray,
     (Person a, Person b) -> {
         return a.getBirthday().compareTo(b.getBirthday());
     }
 );
Arrays.sort(rosterAsArray,
    (a, b) -> Person.compareByAge(a, b)
);
// assuming Person has a static compareByAge method that
// conforms to type of second argument
Arrays.sort(rosterAsArray, Person::compareByAge);

Footnotes

1 code above is copyright of Oracle.