Java: Get hashmap value [closed]

2019-09-30 11:05发布

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条回答
走好不送
2楼-- · 2019-09-30 11:32

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);
查看更多
登录 后发表回答