条目集上的 Java 8 流图

新手上路,请多包涵

我正在尝试对 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 许可协议

阅读 277
2 个回答

简单地将“旧的 for 循环方式”翻译成流:

 private Map<String, String> mapConfig(Map<String, Integer> input, String prefix) {
    int subLength = prefix.length();
    return input.entrySet().stream()
            .collect(Collectors.toMap(
                   entry -> entry.getKey().substring(subLength),
                   entry -> AttributeType.GetByName(entry.getValue())));
}

原文由 Smutje 发布,翻译遵循 CC BY-SA 4.0 许可协议

请制作 Collectors API 的以下部分:

 <K, V> Collector<? super Map.Entry<K, V>, ?, Map<K, V>> toMap() {
  return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue);
}

原文由 Lóránt Miglécz 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题