我有一个字符串和地图的地图,我想在内部地图中更改一个值,但我找不到一个方法来做到这一点。如何在内部地图中找到并更改特定值?
这是我的地图:
String teamName;
Map<String, Integer> players = new HashMap<String,Integer>();
Map<String, Map> teams = new HashMap<String, Map>();
teams.put(teamName, players);
我想在球队地图中增加或减少球员地图内的这个整数值。但由于我的其他代码,我无法直接使用玩家地图,我需要从团队地图中获取它。
答案 0 :(得分:1)
您需要做的就是访问相应的团队地图,然后设置数字。
如果您在整个过程中使用泛型,它会有所帮助:
String teamName = "someteam";
Map<String, Integer> players = new HashMap<String,Integer>();
Map<String, Map<String, Integer>> teams = new HashMap<String, Map<String, Integer>>();
teams.put(teamName, players);
并以teamName
作为关键字更改团队中的玩家数量:
teams.get(teamName).put("somename", 123);
//Or to directly overwrite with an increment:
int currentValue = teams.get(teamName).get("somename");
teams.get(teamName).put("somename", currentValue + 1);
答案 1 :(得分:0)
使用put和get可能很棘手,你应该定义你自己的类,但这是你要问的例子:
Map<String, Integer> players = new HashMap<>();
Map<String, Map<String, Integer>> teams = new HashMap<>();
players.put("Podolski", 0);
players.put("mueller", 0);
teams.put("BayernMuc", players);
System.out.println(players);
System.out.println(teams);
int goals = teams.get("BayernMuc").get("mueller");
teams.get("BayernMuc").put("mueller", 5);
System.out.println(teams);
goals = teams.get("BayernMuc").get("mueller");
teams.get("BayernMuc").put("mueller", ++goals);
System.out.println(players);
System.out.println(teams);