Over a million developers have joined DZone.

Java Holiday Calendar 2016 (Day 10): MapStream

DZone's Guide to

Java Holiday Calendar 2016 (Day 10): MapStream

The open-source class MapStream lets you stream over elements as well as pairs of key value elements, making changes to everything along the way.

· Java Zone ·
Free Resource

Bring content to any platform with the open-source BloomReach CMS. Try for free.

Image title

Today's tip is about the open-source class MapStream, which allows us to stream not only over elements, but over a pair of key value elements and make changes either to the keys, values, or both.

You can find the source code for MapStream here together with some examples of how to use it. It is free, so go ahead and use or copy it in your application! MapStream is a part of Speedment.

With MapStream, you can do this:

Map<String, Integer> numberOfCats = new HashMap<>();

numberOfCats.put("Anne", 3);
numberOfCats.put("Berty", 1);
numberOfCats.put("Cecilia", 1);
numberOfCats.put("Denny", 0);
numberOfCats.put("Erica", 0);
numberOfCats.put("Fiona", 2);

      .filterValue(v -> v > 0)
      .mapKey(k -> k + " has ")
      .mapValue(v -> v + (v == 1 ? " cat." : " cats."))
      .map((k, v) -> k + v)

This would produce the following:

Cecilia has 1 cat.
Berty has 1 cat.
Fiona has 2 cats.
Anne has 3 cats.

Read more about MapStream here.

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.

BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.

java ,mapstream ,open source class ,key value ,elements

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}