简体   繁体   中英

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?

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.

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