简体   繁体   中英

Printing contents of TreeMap which holds more than one TreeSet

I have a map containing keys which are album names and the values are sets of songs on those albums. I want to print the contents and here is my code:

public void printMap() {
    Set<String> albumKeys = this.albumMap.keySet();
    for (String eachSong : this.albumMap.keySet()) {
        System.out.println("The tracks on " + albumKeys + "are: " + albumMap.get(eachSong));
    }
}

The output is:

The tracks on [Genesis, The Dark Side of the Moon ]are: [Home by the Sea, Illegal Alien, It's Gonna Get Better, Just a Job to Do, Mama, Second Home by the Sea, Silver Rainbow, Taking It All Too Hard, That's All] The tracks on [ Genesis, The Dark Side of the Moon]are: [Any Colour You Like, Brain Damage, Eclipse, Money, On the Run, Speak to Me, The Great Gig in the Sky, Us and Them]

As you can see both the album names are printed twice each time. The asterisks indicate the name that should not be printed.

Any help would be appreciated.

The problem with your code is that you print all keys at once every iteration in the loop. As official documentation states

keySet Set keySet() Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations. Returns: a set view of the keys contained in this map

https://docs.oracle.com/javase/8/docs/api/java/util/Map.html

So you need to print only one key at every iteration.

You already have key being in String representation ( eachSong ) in for body:

for (String eachSong: this.albumMap.keySet())

Since you print a name of an album first, you have to replace albumKeys variable with eachSong variable.

But there is inaccuracy in variable name. You actually print album name but for some cause use eachSong name.

As 'Clean code' by Robert C. Martin states,

Choose descriptive and unambiguous names.

So it's better call it, say, eachAlbum .

This code should work:

 Set<String> albumKeys = this.albumMap.keySet();
 for (String eachAlbum: this.albumMap.keySet())
{
System.out.println("The tracks on " + eachAlbum + " are: " + albumMap.get(eachAlbum));
} 

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