javanewbie
javanewbie

Reputation: 1

Iterate through TreeMap - Return a set of all values of the keys of the map

I have a database that maps course names to student id numbers. I need to iterate through the map to create another set that contains all students in the database. This is the code I have so far. Any help would be greatly appreciated!!

//return a set of all students in the school

public Set<Integer> allStudents() {
   Set<Map.Entry<String,Set<Integer>>> entries = database.entrySet();
   Set<Integer> students = new TreeSet<Integer>();

   for (Map.Entry<String,Set<Integer>> pair: entries){ 
       students.add();
    }

    return students;

} // end allStudents

Upvotes: 0

Views: 419

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136162

Your code is correct. Here is a version without iteration

public Set<Integer> allStudents() {
    return new HashSet<Integer>(database.values());
}

Upvotes: 0

Reimeus
Reimeus

Reputation: 159874

You could do:

for (Map.Entry<String, Set<Integer>> pair : entries) {
   students.addAll(pair.getValue());
}

Upvotes: 1

Related Questions