【问题标题】:Reduce code duplicating in functional style java code [closed]减少函数式Java代码中的代码重复[关闭]
【发布时间】:2021-07-07 18:04:42
【问题描述】:

如何减少以下sn-p中的代码重复? Java 12. 提前感谢您

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

【问题讨论】:

  • 我看不到任何减少代码的机会,因为我们无法重构一种方法来实现这一点。
  • @krishnathota 或前两种方法可以just be removed 支持第三种。

标签: java functional-programming code-duplication


【解决方案1】:

使用最后一种方法就足够了。每当您不需要键或值转换时,都可以传递identity 转换器。

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

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

事实上,您的完整解决方案可能如下所示:

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

【讨论】:

    猜你喜欢
    • 2017-08-25
    • 1970-01-01
    • 2013-11-16
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多