Search code examples
javafunctional-programmingcode-duplication

Reduce code duplicating in functional style java code


How to reduce code duplicating in the following snippet? Java 12. Thank you in advance

public <V, RK> Map<RK, V> mapKeys(Map<String, V> input, Function<String, RK> keyTransformer) {
    Map<RK, V> result = new HashMap<>();
    input.forEach((k, v) -> result.put(keyTransformer.apply(k), v));
    return result;
}

public <K, RV> Map<K, RV> mapValues(Map<K, String> input, Function<String, RV> valueTransformer) {
    Map<K, RV> result = new HashMap<>();
    input.forEach((k, v) -> result.put(k, valueTransformer.apply(v)));
    return result;
}

public <RK, RV> Map<RK, RV> mapBothTypes(Map<String, String> input, Function<String, RK> keyTransformer, Function<String, RV> valueTransformer) {
    Map<RK, RV> result = new HashMap<>();
    input.forEach((k, v) -> result.put(keyTransformer.apply(k), valueTransformer.apply(v)));
    return result;
}


Solution

  • The last method shall be sufficient in use. Whenever you don't want a key or a value transformation, you can pass on the identity transformer.

    mapBothTypes(new HashMap<>(), Function.identity(), valueTransformer); // for 'mapValues'
    
    mapBothTypes(new HashMap<>(), keyTransformer, Function.identity()); // for 'mapKeys'
    

    Infact, your complete solution could look like:

    public <RK, RV> Map<RK, RV> transformMap(Map<String, String> input,
                                             Function<String, RK> keyTransformer,
                                             Function<String, RV> valueTransformer) {
        return input.entrySet()
                .stream()
                .collect(Collectors.toMap(e -> keyTransformer.apply(e.getKey()),
                        e -> valueTransformer.apply(e.getValue())));
    }