Day 10, Java Holiday Calendar 2016, MapStream
Today's tips is about the open-source class MapStream that allows us to stream not only over elements but over 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 open-source Speedment, a stream ORM tool and runtime.
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); System.out.println( MapStream.of(numberOfCats) .filterValue(v -> v > 0) .sortedByValue(Integer::compareTo) .mapKey(k -> k + " has ") .mapValue(v -> v + (v == 1 ? " cat." : " cats.")) .map((k, v) -> k + v) .collect(Collectors.joining("\n")) );
This would produce the following:
Cecilia has 1 cat. Berty has 1 cat. Fiona has 2 cats. Anne has 3 cats.
Learn more on MapStream here.
Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.