我正在尝试对 Map
对象中的每个条目执行映射操作。
我需要去掉键的前缀并将值从一种类型转换为另一种类型。我的代码正在从 Map<String, String>
获取配置条目并转换为 Map<String, AttributeType>
( AttributeType
只是对这个类的解释不相关的信息。 .)
我能够使用 Java 8 Streams 得到的最好结果如下:
private Map<String, AttributeType> mapConfig(Map<String, String> input, String prefix) {
int subLength = prefix.length();
return input.entrySet().stream().flatMap((Map.Entry<String, Object> e) -> {
HashMap<String, AttributeType> r = new HashMap<>();
r.put(e.getKey().substring(subLength), AttributeType.GetByName(e.getValue()));
return r.entrySet().stream();
}).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
无法构造一个 Map.Entry
由于它是一个接口,导致创建单个条目 Map
实例和使用 flatMap()
看起来很丑-。
有更好的选择吗?使用 for 循环执行此操作似乎更好:
private Map<String, AttributeType> mapConfig(Map<String, String> input, String prefix) {
Map<String, AttributeType> result = new HashMap<>();
int subLength = prefix.length();
for(Map.Entry<String, String> entry : input.entrySet()) {
result.put(entry.getKey().substring(subLength), AttributeType.GetByName( entry.getValue()));
}
return result;
}
我应该为此避免使用 Stream API 吗?还是我错过了更好的方法?
原文由 Wil Selwood 发布,翻译遵循 CC BY-SA 4.0 许可协议
简单地将“旧的 for 循环方式”翻译成流: