如何获取给定键的值列表并将值列表添加到新创建的列表中?

问题描述 投票:1回答:1

所以我对这个疯狂了。这是一个任务,似乎无法让这一切工作!我有以下HashMap:

HashMap<String, ArrayList<Team>> teams;

(团队是另一个获得团队细节的班级)

我需要做的是从上面的HashMap获取Key(String)的团队列表,并将List分配给我声明的局部变量:

List<Team> results = teams.get(division);

但这是我被卡住的地方。我不知道我打算如何完成这项任务。另外注意“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();

  }

}

**您可以忽略“字符串除法”之后的参数。这些将在以后使用。

java arraylist hashmap
1个回答
1
投票

迭代地图的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

}
© www.soinside.com 2019 - 2024. All rights reserved.