Search code examples
javadictionaryhashmaptreemap

Efficient way to print the entries of a Java Map as a table?


I'm just starting to work with the Java Map data type and I was wondering if there is an easy way to print out all the key-value pairs as a table?

For example, say I want to count the frequencies of a character in a string and store it into a Map.

So the string "all the way down the stream" results in printing to a console the following

Character Frequencies
---------------------
' '        5
'l'        2
't'        3
'h'        2

ect

From what I've found, the toString() on map will return something to the tune of "{ =5, l=2, t=3, h=2}"

Which is great, but building large tables off of the toString structure would be slow. Is there a cleaner, faster way to do this other than String operations?


Solution

  • Assuming your map key-value pair is of type String-Integer, you can iterate through a Map using:

    for (Map.Entry<String, Integer> entry : theMap.entrySet()) {
        entry.getKey(); // gives you the 'Character' key
        entry.getValue(); // gives you the 'Frequencies' value
    }
    

    Of course, you will need to do the pretty printing.