如何转储哈希映射的内容?

如何将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()的东西。

使用HashMap.toString() ( 这里的文档 ):

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

通常,使用Object.toString()来转储这样的数据。

转储数据结构(例如由嵌套映射,数组和集合构成)的好方法是将其序列化为格式化的JSON。 例如,使用Gson(com.google.gson):

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

这将以相当可读的方式打印出最复杂的数据结构。

我经常使用这样的函数(它可能需要扩展以适应Map中其他类型对象的预打印)。

 @SuppressWarnings("unchecked") private static String hashPP(final Map m, String... offset) { String retval = ""; String delta = offset.length == 0 ? "" : offset[0]; for( Map.Entry e : m.entrySet() ) { retval += delta + "["+e.getKey() + "] -> "; Object value = e.getValue(); if( value instanceof Map ) { retval += "(Hash)\n" + hashPP((Map)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 document = new HashMap(); Map student1 = new LinkedHashMap(); document.put("student1", student1); student1.put("name", "Bob the Student"); student1.put("place", "Basement"); List ranking = new LinkedList(); student1.put("ranking", ranking); ranking.add(2); ranking.add(8); ranking.add(1); ranking.add(13); Map scores1 = new HashMap(); student1.put("Scores", scores1); scores1.put("math", "0"); scores1.put("business", "100"); Map student2= new LinkedHashMap(); 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] 

再次。 您可能需要根据您的特定需求进行修改。