Java Lambda Expressions Example

I thought I’d write a quick post to give an example of how to use Java’s Lambda expressions, which were introduced in Java 8. Lamdba expressions provide an easy way (and perhaps more readable, for certain people) to work with lists and arrays. This follows ideas from functional programming languages such as Haskell.

Old method:

List<Person> people = data; // Some data from another source
List<String> names = new ArrayList<>();
 
for (Person person : people) {
    names.add(person.getName());
}

New method (Lambda expression):

List<Person> people = data; // Some data from another source
List<String> names = new ArrayList<>();
 
people.forEach((person) -> names.add(person.getName()));

You can also embed logic like:

people.forEach((person) -> {
    if (!person.getName().isEmpty()) {
        names.add(person.getName());
    }
});

¬†Hopefully the code above is clear, if not feel free to email me or ask a comment and I’ll do my best to answer!

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *