所以我对这个感到疯狂。这是一项作业,似乎根本无法让它发挥作用! 我有以下 HashMap:
HashMap<String, ArrayList<Team>> teams;
(Team是另一个类,用于获取团队的详细信息)
我需要做的是从上面的 HashMap 中获取 Key(String) 的团队列表,并将该列表分配给我声明的局部变量:
List<Team> results = teams.get(division)
;
但这就是我陷入困境的地方。我不知道我该如何完成这项任务。 进一步说明,“除法”是 HashMap 中使用的 Key。 ArrayList 是属于该部门的球队的列表。
我已经尝试过以下内容,但根本无法编译。真的不知道如何让它发挥作用!!
public void recordResult(String division, String teamA, String teamB, int teamAScore, int teamBScore)
{
List<Team> results = teams.get(division);
for (String i : teams.keySet())
{
results = new ArrayList<Team>();
results.add();
}
}
**您可以忽略“字符串除法”之后的参数。这些稍后会用到。
最佳答案
迭代Map的entrySet()
。现在您可以获取该特定键的每个列表并继续下一步。像这样的东西:
for (Entry<String, ArrayList<Team>> entry : teams.entrySet()) {
// extract the value from the key using `teams.get(entry.getKey())`
// proceed further with the value obtained
}
关于java - 如何获取给定键的值列表并将该值列表添加到新创建的列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55883200/