Java: Get hashmap value [closed]

时间秒杀一切 提交于 2019-12-14 03:37:54

问题


I've been looking over the internet but I cant seem to find this answer. I have a hashmap:

public Map<String, Integer> killstreaks = new HashMap<String, Integer>();

Now I want to call the second value, the integer. SO by using the string as a reference, I know I can do this:

killstreaks.get(//idk)

I just need to get my head around on how to get the second value so I can use it to use a formula to work out a value to reward the player.

How it works is that the player kills someone and I store it in this, the player name and the streak they are on, as they kill I add 1 to the streak. When they kill someone I want to give them money according to their streak so I want to use the integer compared to the name, so if I provide the name, it gives the corresponding int, how do I get that? Thanks!


回答1:


This is how you can iterate over your Map:

for (Map.Entry<String, Integer> entry : killstreaks.entrySet()) {
    String key = entry.getKey();
    Integer value = entry.getValue();
    // continue here
}

To get a specific value (Integer) from your Map use:

killstreak.get("yourKey");

Seeing from your comment that you want to increment entries by 1, you can use:

killstreaks.put(key, killstreaks.get(key) + 1);

And as I see you are using Java 8 you can even use the nicer getOrDefault:

killstreaks.put(key, killstreaks.getOrDefault(key, 0) + 1);


来源:https://stackoverflow.com/questions/35405106/java-get-hashmap-value

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