Power of Java 8 Lambda’s

By | April 25, 2016

Most developers hate the boiler plate code needed to do simple tasks. Especially the boilerplate code needed for list manipulations. This ias where the Java 8 lambda’s come into play.

Where in Java 7 a simple clone from an interator in an list would consist out of something similar to:

Iterator<MyObject> it = ....; // Came from a remote call
List<MyObject> myList = new ArrayList<>();
while (it.hasNext()) {
   myList.add(it.next());   
}

This becomes a lot more simple with Java 8:

Iterable<MyObject> it = ...; // Came from a remote call
List<MyObject> myList = new ArrayList<>();
it.forEach(myList::add);

An even better example would be the following use case. Lets say we have a class representing a person and we want to calculate the average age of all people in the collection. Lets compare the needed code for Java 7 and Java 8:

// Person class
public class Person {
   String name;
   int age;
}

double ageAverageJava7() {
   List<Person> people = personRepository.list();
   int totalAge = 0;
   for (Person person : people) {
      totalAge += person.age;
   }
   return totalAge / people.size();
}

double ageAverageJava8() {
   return personRepository.list().stream()
       .map(p -> p.age)
       .average()
       .getAsDouble();
}

As you can see this reduces the amount of code needed and makes the code a lot more readable.

Leave a Reply