reversing keys/values - create new instance of HashMap

风流意气都作罢 提交于 2019-12-12 04:24:23

问题


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.


回答1:


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);

}



回答2:


I think it would be more of something like that:

Map<String,Set<String>> result = new HashMap<String,Set<String>>();
for (Map.Entry<String,Set<String>> entry: salesMap.entrySet()) {
    String cust = entry.getKey();
    Set<String> items = entry.getValue();
    for (String item: items) {
        Set<String> customers = result.get(item);
        if (customers == null) {
            customers = new HashSet<String>();
            result.put(item, customers);
        }
        customers.add(cust);
    }
}


来源:https://stackoverflow.com/questions/2475663/reversing-keys-values-create-new-instance-of-hashmap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!