Reputation: 1
I have a map of a string and a map, and I want to change a value inside the inner map but I couldn't find a method to do that. How can I reach and change the specific value inside the inner map?
here's my maps:
String teamName;
Map<String, Integer> players = new HashMap<String,Integer>();
Map<String, Map> teams = new HashMap<String, Map>();
teams.put(teamName, players);
I want to increase or decrease this integer value inside the players map from the teams map. But I cannot use the players map directly because of the rest of my code, I need to reach it from the teams map.
Upvotes: 0
Views: 77
Reputation: 48258
with the map put and get can be tricky, you should define yyour own class, but this is ans example of what you are asking:
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);
Upvotes: 0
Reputation: 45319
All you need to do is access the appropriate team's map, then set the number.
It will help if you used generics throughout:
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);
And to change the number of players in team with teamName
as key:
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);
Upvotes: 1