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)))...
???
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)...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With