Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Java 8 stream to convert a map's key+value into a new value using a function that receives two params?

I have a static method String Converter.convert(String, Integer).

I also have a map: Map<String, Integer> map.

I'd like to run over the map and convert each entry to a string using the convert method and continue using each converted string.

I can do it this way:

map.entrySet().stream().map(e -> Converter.convert(e.getKey(), e.getValue()))....;

Is there a way to do it more intuitive? Something like the following?

map.stream(Converter::convert)...???

or

map.stream((k, v) -> Converter.convert(k, v)))...???

like image 335
AlikElzin-kilaka Avatar asked Sep 25 '16 13:09

AlikElzin-kilaka


1 Answers

You can create an adapter static method in some utility class like this:

public class Functions {
    public static <K, V, R> Function<Map.Entry<K, V>, R> entryFunction(
            BiFunction<? super K, ? super V, ? extends R> fn) {
        return entry -> fn.apply(entry.getKey(), entry.getValue());
    }
}

Now you can use it like this:

import static Functions.*;

map.entrySet().stream().map(entryFunction(Converter::convert))...

An alternative solution would be to use some third-party library which extends Java 8 Stream API. One of such libraries is free StreamEx library which I wrote. It contains a special class EntryStream<K, V> which implements Stream<Entry<K, V>> and provides additional handy methods including mapKeyValue which is one you need:

EntryStream.of(map).mapKeyValue(Converter::convert)...
like image 164
Tagir Valeev Avatar answered Sep 28 '22 00:09

Tagir Valeev