Skip to content

Instantly share code, notes, and snippets.

@irbull
Created March 25, 2014 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save irbull/9770904 to your computer and use it in GitHub Desktop.
Save irbull/9770904 to your computer and use it in GitHub Desktop.
Java 8 Lambda example
In this simple example, we are taking a List<String> of names, sorting them, creating Person objects and printing the result. The first way uses single line lambda expressions:
names.stream().sorted((o1, o2) -> o1.compareTo(o2)).
map(name -> new Person(name)).
forEach(p -> System.out.println(p.getName()));
The second one wraps each expression in a bracket and makes the types explicit:
names.stream().sorted(( String o1, String o2 ) ->
{
return o1.compareTo(o2);
}
).map((String name) ->
{
return new Person(name);
}
).forEach((Person p) ->
{
System.out.println(p.getName());
}
);
@robinst
Copy link

robinst commented Mar 26, 2014

The following results in a syntax error:

names.stream().map(name -> new Person(name); "foo")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment