Skip to content

Instantly share code, notes, and snippets.

@jiffle
Last active February 17, 2017 15:53
Show Gist options
  • Save jiffle/7acd1359b4828fe0b83649db51420448 to your computer and use it in GitHub Desktop.
Save jiffle/7acd1359b4828fe0b83649db51420448 to your computer and use it in GitHub Desktop.
Cheatsheet for Java 8 Lambda syntax

Java Lambda Syntax

As an expression

(Person p) -> p.getGender() == Person.Sex.MALE
    && p.getAge() >= 18
    && p.getAge() <= 25

As a local variable

@FunctionalInterface
public interface SomeFunction {
    public void doWork();
}

SomeFunction lambdaName = () -> {...};

As a method parameter

@FunctionalInterface
public interface SomeFunction {
    public void doWork();
}

void someMethodThatTakesALambda(SomeFunction lambdaName) {...}

As an argument to a method call

someObject.someMethodThatTakesALambda ((ParameterClass p) -> {...});

Java Streams Usage

Transforming a list

return list.stream().map( this::buildItem).collect( Collectors.toList());

Java Optional Usage

Conditional test for non-null value

Invoking a method on the variable with no return value

opt.ifPresent(this::print);

Passing the (non-null) variable into method with no return value

opt.ifPresent(x -> print(x));

Passing the (non-null) variable into method and returning a result (and with value for null)

opt.map(y -> y ^ 2).orElse( -1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment