条目集上的Java 8流映射 [英] Java 8 stream map on entry set
问题描述
我正在尝试对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屋!