Tuesday, 21 April 2020

Transform Map to Map

Using Generics and Collections.toMap function we can convert Map<X, Y> to Map<X, Z>.

Below snippet takes a map of type <X,Y> and transform it to Map<X,Z> by applying a function on Y (f(Y) =Z).

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())));
}

Find the below working application.

App.java
package com.sample.app;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class App {

 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())));
 }

 public static void main(String args[]) {

  @SuppressWarnings("unchecked")
  Map<Integer, String> map = new HashMap() {
   {
    put(1, "1");
    put(2, "4");
    put(3, "6");
   }

  };

  Map<Integer, Integer> result = transform(map, data -> Integer.parseInt(data));

  System.out.println("map : " + map);
  System.out.println("result : " + result);

 }

}

Output
map : {1=1, 2=4, 3=6}
result : {1=1, 2=4, 3=6}



You may like

No comments:

Post a Comment