[英]Create HashMap from List<String>
I have a few simple JSON files that have syntax 我有一些具有语法的简单JSON文件
"key1": "value1"
"key2": "value2"
etc. 等等
I need to create a Map from each of them, and then merge them into one. 我需要从它们每个创建一个Map,然后将它们合并为一个。 The following code works as is supposed to: 以下代码按预期工作:
private TranslationBundle assembleBundle(List<String> translations) {
TranslationBundle translationBundle = new TranslationBundle();
Map<String, String> bundledTranslationMap = new HashMap<>();
translations.forEach(translation -> {
bundledTranslationMap.putAll(getSingleTranslationMap(translation).);
});
translationBundle.setTranslationMap(bundledTranslationMap);
return translationBundle;
}
private Map<String, String> getSingleTranslationMap(String translation){
ObjectMapper mapper = new ObjectMapper();
try{
return mapper.readValue(translation, new TypeReference<Map<String, String>>(){});
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
What I want to achieve is to rewrite the code in the assembleBundle
method into a more functional one, like 我要实现的是将assembleBundle
方法中的代码重写为功能更强大的代码,例如
translations.stream().
map(this::getSingleTranslationMap)
.collect(collect to single HashMap);
In the collect()
method, as far as I know, I have to somehow access the key and value for each result of getSingleTranslationMap
. 据我所知,在collect()
方法中,我必须以某种方式访问getSingleTranslationMap
每个结果的键和值。 Since there is no variable name assigned to the result of this method, how should it be done? 由于没有为该方法的结果分配变量名,应该怎么做? Maybe I'm trying a wrong approach at all? 也许我正在尝试一种错误的方法?
You can transform the individual Map
s returned by getSingleTranslationMap
into a Stream
of map entries, and collect them into a single Map
: 您可以将getSingleTranslationMap
返回的各个Map
转换为Map
条目的Stream
,并将它们收集到一个Map
:
Map<String, String> bundledTranslationMap =
translations.stream()
.flatMap(translation -> getSingleTranslationMap(translation).entrySet()
.stream())
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
Of course, if getSingleTranslationMap
returns a Map
with a single Entry
, it might make more sense for that method to return a Map.Entry
instead of a Map
, which would simplify the above Stream
pipeline. 当然,如果getSingleTranslationMap
返回具有单个Entry
的Map
,则该方法返回Map.Entry
而不是Map
可能更有意义,这将简化上述Stream
管道。
PS, if duplicate keys are possible, you should add a merge function to the toMap()
call. PS,如果可能有重复的键,则应将合并功能添加到toMap()
调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.