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