入口集上的 Java 8 流映射 [英] Java 8 stream map on entry set

查看:19
本文介绍了入口集上的 Java 8 流映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对 Map 对象中的每个条目执行映射操作.

I'm trying to perform a map operation on each entry in a Map object.

我需要从键中取出前缀并将值从一种类型转换为另一种类型.我的代码从 Map<String, String> 获取配置条目并转换为 Map<String, AttributeType> (AttributeType 只是一个类持有一些信息.进一步的解释与这个问题无关.)

I need to take a prefix off the key and convert the value from one type to another. My code is taking configuration entries from a Map<String, String> and converting to a Map<String, AttributeType> (AttributeType is just a class holding some information. Further explanation is not relevant for this question.)

使用 Java 8 Streams 我所能想到的最好的方法如下:

The best I have been able to come up with using the Java 8 Streams is the following:

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(),看起来很难看.

Being unable to construct an Map.Entry due to it being an interface causes the creation of the single entry Map instance and the use of flatMap(), which seems ugly.

还有更好的选择吗?使用 for 循环执行此操作似乎更好:

Is there a better alternative? It seems nicer to do this using a for loop:

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 吗?还是我错过了更好的方法?

Should I avoid the Stream API for this? Or is there a nicer way I have missed?

推荐答案

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

Simply translating the "old for loop way" into streams:

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

这篇关于入口集上的 Java 8 流映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆