简体   繁体   中英

trouble adding values to a new List from a list stored in a hashmap - Java

I've been hunting around for a way to do this and it is driving me mad!

What I'm trying to do is as follows:

I have a HashMap:

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

The values I'm assigning to the hashmap are:

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"}
};

the key sting is the name of an event and the List is a list of competitors. I want to build a new list of all the competitors.

So I've tried various things like:

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

and then iterating through the 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());

To see what vales I get, which is fine, but I cannot then add them a new list? I know I'm missing something obvious any suggestions?

What I think you're saying is that you have a map of String to List<String> and you want to accumulate all of the List<String> into a single long list. If that's the case:

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

eventsToCompetitors = ...

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

Is this what you mean?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM