Map.Entry methods for streams

Stephen Colebourne scolebourne at joda.org
Fri Jan 15 13:05:51 UTC 2016


I've had a morning of discussion about streaming Map this morning. While
there is clearly no appetite for a JDK MapStream right now, it does seem
that two additional methods on Map.Entry could help.

Two of the common cases when streaming over Map.Entry are to transform the
keys and to transform the values. Currently, the code is as follows:

hashMap.entrySet().stream()
  .map(e -> new AbstractMap.SimpleImmutableEntry(e.getKey(),
e.getValue().transformed()))
  ...

This isn't really very pleasant.

Adding a default method to Map.Entry would help:

hashMap.entrySet().stream()
  .map(e -> e.mapValue(v -> v.transformed()))
  ...

Implementation of the mapValue method is left to the reader, but it isn't
hard. A mapKey() method would also be needed. Note that both are designed
to work without mutating the map (returning a new entry).

Finally, the Collectors class could do with a new method entriesToMap()
that collects a stream of Map.Entry back into a Map.

While these proposals are not as powerful as a MapStream, they would smooth
some rough edges in the API when working with maps.

Stephen



More information about the core-libs-dev mailing list