Using Streams of Map.Entry to Preserve Initial Values after Mapping

suggest change

When you have a Stream you need to map but want to preserve the initial values as well, you can map the Stream to a Map.Entry<K,V> using a utility method like the following:

public static <K, V> Function<K, Map.Entry<K, V>> entryMapper(Function<K, V> mapper){
    return (k)->new AbstractMap.SimpleEntry<>(k, mapper.apply(k));
}

Then you can use your converter to process Streams having access to both the original and mapped values:

Set<K> mySet;
Function<K, V> transformer = SomeClass::transformerMethod;
Stream<Map.Entry<K, V>> entryStream = mySet.stream()
    .map(entryMapper(transformer));

You can then continue to process that Stream as normal. This avoids the overhead of creating an intermediate collection.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Streams:
* Using Streams of Map.Entry to Preserve Initial Values after Mapping

Table Of Contents
2 Streams
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap