【问题标题】:How can I obtain the list of values for a given key and add the list of values to a newly created list?如何获取给定键的值列表并将值列表添加到新创建的列表中?
【发布时间】:2019-04-27 17:37:28
【问题描述】:

所以我要疯了。这是一个任务,似乎根本无法让它工作! 我有以下 HashMap:

HashMap<String, ArrayList<Team>> teams;

(Team 是另一个类来获取团队的详细信息)

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

List&lt;Team&gt; 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();

  }

}

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

【问题讨论】:

  • 这里需要递归..

标签: java arraylist hashmap


【解决方案1】:

遍历地图的entrySet()。现在您可以获取该特定键的 each 列表并继续进行。比如:

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

}

【讨论】:

    猜你喜欢
    • 2021-09-25
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多