减少函数式代码中的代码重复 java 代码
Reduce code duplicating in functional style java code
如何减少以下代码段中的代码重复? 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;
}
最后一种方法应该足够用了。每当您不需要键或值转换时,您可以传递 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())));
}
如何减少以下代码段中的代码重复? 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;
}
最后一种方法应该足够用了。每当您不需要键或值转换时,您可以传递 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())));
}