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().
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);
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.
Use HashMap.toString()
(docs here):
System.out.println("HASH MAP DUMP: " + myHashMap.toString());
Generally, use Object.toString()
to dump data like this.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With