无法从存储在hashmap中的列表中将值添加到新列表中 - Java

时间:2012-04-18 07:49:27

标签: java arraylist hashmap

我一直在寻找一种方法来做这件事,这让我很生气!

我要做的是如下:

我有一个HashMap:

qualifiedCompetitors = new HashMap<String, List<String>>();

我分配给hashmap的值是:

String[] events = {"Helicopter", "Amphibious", 
                     "4x4", "Fire Engine"};

String[][] competitors = 
{
   {"Greg", "Will", "Fleur", "Bill", "Bella", "Sally", "Olive", "Sal", "Dora", "Chas"}, 
   {"Yuri", "Abe", "Tim", "Fleur", "Bonnie", "Vera", "Ed", "Dan", "Jill", "Rose", "Zoe"}, 
   {"Tim", "Fleur", "Will",  "Bill", "Bella", "Dan", "Jill", "Rose", "Greg",  "Abe", "Sally", "Yuri", "Olive", "Sal", "Jim"}, 
   {"Jill", "Rose", "Greg", "Abe", "Bonnie", "Vera", "Ed", "Zoe", "Ben", "Freda", "Chuck", "Fred"}
};

key sting是一个事件的名称,List是一个竞争者列表。我想建立一个所有竞争者的新名单。

所以我尝试过各种各样的事情:

ListOfAllqualifiedCompetitors = new ArrayList(qualifiedCompetitors.values());

然后遍历hashmap:

Collection allCompetitors = qualifiedCompetitors.values();

System.out.println("Values of Collection created from Hashtable are :");
//iterate through the collection
Iterator itr = allDrivers.iterator();
while(itr.hasNext())
  System.out.println(itr.next());

要查看我得到的vales,这很好,但我不能再将它们添加到新列表中?我知道我遗漏了一些明显的建议吗?

2 个答案:

答案 0 :(得分:1)

想到你所说的是你有StringList<String>的地图,并且你希望将所有List<String>累积到单长列表。如果是这样的话:

final Map<String, List<String>> eventsToCompetitors;
final List<String> allCompetitors;

eventsToCompetitors = ...

allCompetitors = new ArrayList<String>();
for (Collection<String> competitors : eventsToCompetitors.values())
{
  allCompetitors.addAll(competitors);
}

答案 1 :(得分:0)

List<String> allCompetitors = new ArrayList<String>();
for(Set<String> competitors : qualifiedCompetitors.values()) {
    allCompetitors.addAll(competitors);
}

这是你的意思吗?