Java 8 :: Project Lambda presentation

Today at work I held a presentation about lambdas and Stream API coming to Java 8 for all coworkers at FINN.no.

The presentation is uploaded to slide-share:

(if you rather like the source feel free to get it on github)

Advertisements

Java 8: joining strings with Stream API

I this brief blog post I show how to loop over a collection of persons and build a string built by their names. The new Java 8 Stream API makes this really easy, combined with lambda expressions, explained in a previous post.

Problem description:
– Given a list of persons
– Build a string, we should follow this format: “age1:name1, age2:name2”
– We should only include adult persons (age > 18)
– Sort the names by age

//Data
List<Person> persons = new ArrayList<>();
persons.add(new Person("Ola Hansen", 21));
..

//Solution
String names = persons.stream()
  .filter(p -> p.getAge() > 18)
  .sorted((p1, p2) -> p1.getAge() - p2.getAge())
  .map(p -> p.getAge() + ":" + p.getName())
  .collect(Collectors.joining(", "));

//Result
"21:Ola Hansen, 28:Ivar Østhus, 29:Kari Normann, 42:Donald Duck"

This problem is really easy to solve using the new Stream API, as shown in code example above. The key to the solution is the joining-collector provided as a ready to use Collector. The joining-collector uses StringBuilder under the hood, to build up the resulting String. How would the solution look like with imperative styled for-loops? How many garbage variables would you need?

The example touches multiple new concepts, such as filter, sorted, map, collect, introduced in the Java 8 Stream API. Later I will write about the Stream API more deeply.