我经常使用这样的函数(它可能需要扩展以适应 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]
再次。您可能需要根据您的特定需求对其进行修改。