如何将Java HashMap(或任何其他内容)的内容转储到STDOUT?
例如,假设我有一个具有以下结构的复杂HashMap:
( student1 => Map( name => Tim,
Scores => Map( math => 10,
physics => 20,
Computers => 30),
place => Miami,
ranking => Array(2,8,1,13),
),
student2 => Map (
...............
...............
),
............................
............................
);
所以我想将它打印到屏幕上,以便了解数据结构。 我正在寻找类似于PHP的var_dump()或Perl的dumper()的东西。
答案 0 :(得分:22)
使用HashMap.toString()
(docs here):
System.out.println("HASH MAP DUMP: " + myHashMap.toString());
通常,使用Object.toString()
来转储这样的数据。
答案 1 :(得分:2)
转储数据结构(例如由嵌套映射,数组和集合构成)的好方法是将其序列化为格式化的JSON。例如,使用Gson(com.google.gson):
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(dataStructure));
这将以相当可读的方式打印出最复杂的数据结构。
答案 2 :(得分:0)
我经常使用这样的函数(它可能需要扩展以适应Map中其他类型对象的预打印)。
@SuppressWarnings("unchecked")
private static String hashPP(final Map<String,Object> m, String... offset) {
String retval = "";
String delta = offset.length == 0 ? "" : offset[0];
for( Map.Entry<String, Object> e : m.entrySet() ) {
retval += delta + "["+e.getKey() + "] -> ";
Object value = e.getValue();
if( value instanceof Map ) {
retval += "(Hash)\n" + hashPP((Map<String,Object>)value, delta + " ");
} else if( value instanceof List ) {
retval += "{";
for( Object element : (List)value ) {
retval += element+", ";
}
retval += "}\n";
} else {
retval += "["+value.toString()+"]\n";
}
}
return retval+"\n";
} // end of hashPP(...)
因此遵循代码
public static void main(String[] cmd) {
Map<String,Object> document = new HashMap<String, Object>();
Map<String,Object> student1 = new LinkedHashMap<String, Object>();
document.put("student1", student1);
student1.put("name", "Bob the Student");
student1.put("place", "Basement");
List<Integer> ranking = new LinkedList<Integer>();
student1.put("ranking", ranking);
ranking.add(2);
ranking.add(8);
ranking.add(1);
ranking.add(13);
Map<String,Object> scores1 = new HashMap<String, Object>();
student1.put("Scores", scores1);
scores1.put("math", "0");
scores1.put("business", "100");
Map<String,Object> student2= new LinkedHashMap<String, Object>();
document.put("student2", student2);
student2.put("name", "Ivan the Terrible");
student2.put("place", "Dungeon");
System.out.println(hashPP(document));
}
将产生输出
[student2] -> (Hash)
[name] -> [Ivan the Terrible]
[place] -> [Dungeon]
[student1] -> (Hash)
[name] -> [Bob the Student]
[place] -> [Basement]
[ranking] -> {2, 8, 1, 13, }
[Scores] -> (Hash)
[math] -> [0]
[business] -> [100]
再次。您可能需要根据您的特定需求进行修改。