Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dump the contents of a hash map?

How can I dump the contents of a Java HashMap(or any other), for example to STDOUT ?

As an example, suppose that I have a complex HashMap of the following structure :

( student1 => Map( name => Tim,         
                   Scores => Map( math => 10,
                                  physics => 20,
                                  Computers => 30),
                   place => Miami,
                   ranking => Array(2,8,1,13),
                  ),
 student2 => Map ( 
                   ...............
                   ...............
                 ),
............................
............................
);

So I would like to print it to the screen in order to get an idea about the data structure. I am looking for something similar to PHP's var_dump() or Perl's dumper().

like image 346
M-D Avatar asked Jun 13 '12 03:06

M-D


People also ask

How do I get something out of a HashMap?

The Java HashMap remove() method removes the mapping from the hashmap associated with the specified key. The syntax of the remove() method is: hashmap. remove(Object key, Object value);

How do I print HashMap values?

Print HashMap Elements in Java This is the simplest way to print HashMap in Java. Just pass the reference of HashMap into the println() method, and it will print key-value pairs into the curly braces.


2 Answers

Use HashMap.toString() (docs here):

System.out.println("HASH MAP DUMP: " + myHashMap.toString());

Generally, use Object.toString() to dump data like this.

like image 97
pb2q Avatar answered Oct 04 '22 17:10

pb2q


A good way to dump data structures (e.g. made of nested maps, arrays and sets) is by serializing it to formatted JSON. For example using Gson (com.google.gson):

Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(dataStructure));

This will print out the most complex data structures in a fairly readable way.

like image 29
jox Avatar answered Oct 04 '22 18:10

jox