hashmap 插入回调

问题描述 投票:0回答:1

我正在制作一个 Spring 应用程序,该应用程序将使用户能够在游戏等待大厅中等待。 (像队列一样)

所以我会有4个地区,美洲,非洲,欧盟和中东。

我正在考虑创建一个类似的地图,

UserId1 - Region1
UserId2 - Region2
UserId3 - Region2
UserId4 - Region4
UserId5 - Region3

插入区域 3 后,地图的新输出将是:

UserId3 - Region2

并且会把剩下的还给我。

在每个“.put()”处,我想做一个 beforecallback 来查看 userid 是否已经存在。 (所以它不会添加相同的 uid 两次)

然后在‘.put()’之后 我想看看每个区域是否至少存在一个实例,匹配来自 4 个不同区域的 4 个用户(从顶部开始,以便匹配一直等待最多时间的用户),返回该信息并清理/释放这 4 个实例从地图上看。

Map<Country, userid> hm 

            = new HashMap<Integer, String>(); 

    hm.put(userId1, Region1); 
    hm.put(userId2, Region2); 
    hm.put(userId3, Region2); 
    hm.put(userId4, Region4); 
    hm.put(userId5, Region3); 


    for (Map.Entry<String, Integer> me : //this might be used to check if a userId exists, so when there is a put operation I can return error

        System.out.print(me.getKey() + ":"); 
        System.out.println(me.getValue()); 

    } 

是否有地图类型的回调,我可以在每次插入时调用?例如,可能会从“国家/地区”获取所有重复值的计数?

对此有什么好的方法吗?我如何在代码中实现这个?

我想为每次插入实现回调,如何在代码中实现这一点?

更新:

似乎检查每个区域是否至少存在一次,我可以做

布尔值 containsAll = false;

包含值(区域1) 包含值(区域2) 包含值(区域 3) 包含值(区域4)

java callback
1个回答
0
投票

您可能不需要回电。只需定义一个方法来检查 userId 是否已在地图中:

boolean addUser(String userId, Integer regionId) {
    if (hm.containsKey(userId)) return false; // Or throw an exception if you prefer

    hm.put(userId, regionId);
    return true;
}

对于后一部分,我不太明白你到底想检查什么。您想要检查是否有来自特定区域的用户,或者统计来自特定区域的所有用户,或者两者兼而有之?您可能需要一个单独的方法

© www.soinside.com 2019 - 2024. All rights reserved.