Java:获取hashmap值 [英] Java: Get hashmap value

查看:178
本文介绍了Java:获取hashmap值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在查看互联网,但我似乎找不到这个答案。我有一个HashMap:

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

现在我想调用第二个值,整数。因此,通过使用字符串作为参考,我知道我可以做到这一点:

  killstreaks.get(// idk)

我只需要知道如何获得第二个值,以便我可以使用它来使用公式来计算奖励玩家的价值。



它的工作原理是玩家杀死一个人,然后我将它存储在这个玩家的名字和他们所在的连胜中,因为他们杀了我给连胜加1 。当他们杀了一个人,我想给他们钱,根据他们的条纹,所以我想用整数相比名称,所以如果我提供的名称,它给出了相应的int,我怎么得到的?感谢!

解决方案

这是您可以遍历 Map
$ (Map.Entry< String,Integer>条目:killstreaks.entrySet()){
String key = entry.getKey(); b $ b

  
整数值= entry.getValue();
//在这里继续
}

获取特定值( killstreak.get( yourKey);

从您的评论看来,您希望将条目增加1,您可以使用:

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

正如我看到您使用的是Java 8,您甚至可以使用更好的 getOrDefault
$ b

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


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!

解决方案

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

这篇关于Java:获取hashmap值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆