Java 8 stream map on entry set(入口集上的 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 流映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:入口集上的 Java 8 流映射
基础教程推荐
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01