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

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

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

"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.


One thought on “Java 8: joining strings with Stream API

  1. Pingback: Streaming CSV files with the Java 8 Stream API | Developer writing about stuff

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s