【问题标题】:Reversing a HashMap <String, Object> to different Sets and/or Lists将 HashMap <String, Object> 反转为不同的集合和/或列表
【发布时间】:2012-07-31 06:01:51
【问题描述】:

我会尽可能简单地解释我被困住的观点。

基本上,我正在尝试实施一种解决方案来处理用户数据。

我有一个类似&lt;String, Object&gt; 的映射,它将用户 ID 存储为键,将用户对象存储为值。用户对象有一些字段,如位置、姓名、年龄等。

通过使用地图,我想要一些集合或其他地图来分类用户数据。例如,我正在尝试获取另一张地图,例如&lt;String, Set&lt;String&gt;&gt;,它将存储一组居住在同一位置的用户,依此类推。

我尝试了一些技巧,并检查了一些链接,如 thisthis 以及其他一些链接,还尝试实现一些用于反转的基本代码

Set<String> userid = new HashSet<String>();
Map<String, Set<String>> returnvalue = new HashMap<String, Set<String>>();
HashMap<String, String> userReason = convertForReason();
for (Entry<String, String> entry : userReason.entrySet()) {
    userid.add(entry.getKey());
}

但我不知道如何创建新地图&lt;String. Set&lt;String&gt;&gt;,有什么想法可以实现吗?或针对此类问题的其他解决方案?

更新:

这是我为自己的问题找到的:

Map> returnValue = new HashMap>(); HashSet reasonSet = new HashSet();

    for(String userId : userData.keySet()){
        UserObject obj = userData.get(userId);
        String location = obj.getLocation();
        String username = obj.getUserid(); 
        if(returnValue.get(location)==null){
            reasonSet = new HashSet<String>();
            reasonSet.add(username);
            returnValue.put(reason, reasonSet);
        }else{
            HashSet<String> tmp = returnValue.get(location); 
            tmp.add(username);
            returnValue.put(location, tmp);
        }

感谢 Byter 给了我洞察力和更好的想法来解决这个问题 :) 我不太确定如果尺寸太大会如何影响性能

【问题讨论】:

    标签: java oop map hashmap reverse


    【解决方案1】:

    假设您将位置作为用户数据,并且您希望给定位置的不同用户...

     Map<String, Set<String>> returnvalue = new HashMap<String, Set<String>>();
        Map<String, UserObject> userData = getUserData();
    
        for (String userId : userData.keySet()) {
            UserObject obj = userData.get(userId);
            String location = obj.getLocation();
            Set<String> usersInGivenLocation = returnvalue.get(location);
            if(usersInGivenLocation == null) {
               usersInGivenLocation = new HashSet<String>();
               returnvalue.put(userId,usersInGivenLocation);
            }
            usersInGivenLocation.add(userId);
        }
    

    我希望这是你想要的......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-20
      • 2018-07-16
      • 2017-02-06
      • 2017-11-04
      • 2022-11-01
      • 2014-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多