Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I transform a Map<K,V1> to another Map<K,V2> using a map of functions in Java 8?

I want to transform a Map<String, Integer> to another Map<String, Long> using a map of functions in Java 8, matching the data with the functions by key in both maps. You can assume that both maps have the same keys.

I tried the following approach:

Map<String, Integer> inputData = new HashMap<>();
inputData.put("A",8);
inputData.put("B",7);
inputData.put("C",6);

Map<String, Function<Integer, Long>> transformers = new HashMap<>();
transformers.put("A", x -> x*2L);
transformers.put("B", x -> x+3L);
transformers.put("C", x -> x+11L);

Map<String, Long> mappedData = inputData.entrySet().stream()
    .map(entry -> new AbstractMap.SimpleEntry<>(
         entry.getKey(),
         transformers.get(entry.getKey()).apply(entry.getValue())))
    .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));

Expected result: {A=16, B=10, C=17}.

Is there any simpler way of expressing "apply map of transformers to the map of inputData matching by key" in Java Streams API?

like image 651
tafit3 Avatar asked Jan 13 '16 11:01

tafit3


2 Answers

You may transform directly in the collector:

Map<String, Long> mappedData = inputData.entrySet().stream()
    .collect(toMap(Map.Entry::getKey, 
            entry -> transformers.get(entry.getKey()).apply(entry.getValue())));

Such solution is shorter and does not create intermediate objects.

Were your inputData had the same value type (Map<String, Long>), you could perform the transformation in-place:

inputData.replaceAll((key, value) -> transformers.get(key).apply(value));
like image 197
Tagir Valeev Avatar answered Nov 01 '22 21:11

Tagir Valeev


You can also start from transformers map itself, which looks slightly easier:

    Map<String, Long> collect = transformers.entrySet().stream()
            .collect(toMap(Map.Entry::getKey, 
                    e -> e.getValue().apply(inputData.get(e.getKey()))));
like image 2
Andremoniy Avatar answered Nov 01 '22 22:11

Andremoniy