I know how to \"transform\" a simple Java List
from Y
-> Z
, i.e.:
List x;
List y = x.stre
Does it absolutely have to be 100% functional and fluent? If not, how about this, which is about as short as it gets:
Map<String, Integer> output = new HashMap<>();
input.forEach((k, v) -> output.put(k, Integer.valueOf(v));
(if you can live with the shame and guilt of combining streams with side-effects)
The declarative and simpler solution would be :
yourMutableMap.replaceAll((key, val) -> return_value_of_bi_your_function); Nb. be aware your modifying your map state. So this may not be what you want.
Cheers to : http://www.deadcoderising.com/2017-02-14-java-8-declarative-ways-of-modifying-a-map-using-compute-merge-and-replace/
A generic solution like so
public static <X, Y, Z> Map<X, Z> transform(Map<X, Y> input,
Function<Y, Z> function) {
return input
.entrySet()
.stream()
.collect(
Collectors.toMap((entry) -> entry.getKey(),
(entry) -> function.apply(entry.getValue())));
}
Example
Map<String, String> input = new HashMap<String, String>();
input.put("string1", "42");
input.put("string2", "41");
Map<String, Integer> output = transform(input,
(val) -> Integer.parseInt(val));