我有如下地图
Map<String, String> values = new HashMap<String, String>();
values.put("aa", "20");
values.put("bb", "30");
values.put("cc", "20");
values.put("dd", "45");
values.put("ee", "35");
values.put("ff", "35");
values.put("gg", "20");
Run Code Online (Sandbox Code Playgroud)
我想以格式创建新地图 Map<String,List<String>> ,示例输出将为
"20" -> ["aa","cc","gg"]
"30" -> ["bb"]
"35" -> ["ee","ff"]
"45" -> ["dd"]
Run Code Online (Sandbox Code Playgroud)
我可以通过迭代实体来做
Map<String, List<String>> output = new HashMap<String,List<String>>();
for(Map.Entry<String, String> entry : values.entrySet()) {
if(output.containsKey(entry.getValue())){
output.get(entry.getValue()).add(entry.getKey());
}else{
List<String> list = new ArrayList<String>();
list.add(entry.getKey());
output.put(entry.getValue(),list);
}
}
Run Code Online (Sandbox Code Playgroud)
使用流可以做得更好吗?
Era*_*ran 18
groupingBy可用于按值对键进行分组.如果在没有a的情况下使用mapping Collector它,它会将Streammap条目(Stream<Map.Entry<String,String>>)转换为a Map<String,List<Map.Entry<String,String>>,它接近你想要的,但不完全.
为了使输出的值Map是一个List原始的钥匙,你必须链mapping Collector到groupingBy Collector.
Map<String,List<String>> output =
values.entrySet()
.stream()
.collect(Collectors.groupingBy(Map.Entry::getValue,
Collectors.mapping(Map.Entry::getKey,
Collectors.toList())));
System.out.println (output);
Run Code Online (Sandbox Code Playgroud)
输出:
{45=[dd], 35=[ee, ff], 30=[bb], 20=[aa, cc, gg]}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1137 次 |
| 最近记录: |