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


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 =

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