反转键/值 - 创建HashMap的新实例 [英] reversing keys/values - create new instance of HashMap

查看:128
本文介绍了反转键/值 - 创建HashMap的新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现存的HashMap实例,简称为sale (它是Map< String,Set< String>>)我用它来记录客户和项目历史。

有没有办法创建一个新的HashMap实例,这有效地反转了这种用法?即将每件物品作为一个唯一的钥匙购买,并将相应的价值显示为购买该产品的顾客的字符串集合。我怀疑有一个简单的过程使用keySet()以某种方式迭代销售映射,但我无法看到如何执行此操作。
任何帮助将不胜感激。

解决方案

你的意思是你想要一些像Map,String>的东西!



您可以迭代现有地图并将反转键值放入新地图中。例如: p>

 映射< Set< String>,String> somemap = new HashMap< Set< String>,String>(); 
foreach(Map.entry entry:existingMap.entrySet()){
Set< String> value = entry.getValue();
String key = entry.getKey();
somemap.put(value,key);

}


I’ve got an existing instance of HashMap simply called sale (it is Map<String, Set<String>>) I use it to log customers and items history.

Is there a way to create a new instance of HashMap, that effectively reverses this usage? i.e will show each item purchased as a unique key and the corresponding value as a String set of the customers that have purchased that product. I suspect there is a simple process using keySet() in some way to iterate over the sales map but I just can’t see how to do this. Any help would be much appreciated.

解决方案

do you mean you want some thing like Map, String> !!

Thn you can iterate over existing map and put reversed key values in a new map

Example:

Map<Set<String>, String> somemap = new HashMap<Set<String>, String>();
foreach(Map.entry entry : existingMap.entrySet()) {
  Set<String> value = entry.getValue();
  String key = entry.getKey();
  somemap.put(value,key);

}

这篇关于反转键/值 - 创建HashMap的新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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