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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11007860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 03:23:48  来源:igfitidea点击:

How do I dump the contents of a hash map?

javadata-structures

提问by M-D

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

如何转储 Java HashMap(或任何其他)的内容,例如转储到 STDOUT ?

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

例如,假设我有一个具有以下结构的复杂 HashMap:

( 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().

所以我想把它打印到屏幕上,以便了解数据结构。我正在寻找类似于 PHP 的 var_dump() 或 Perl 的 dumper() 的东西。

回答by pb2q

Use HashMap.toString()(docs here):

使用HashMap.toString()此处为文档):

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

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

一般Object.toString()用来转储这样的数据。

回答by jox

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):

转储数据结构(例如由嵌套映射、数组和集合组成)的一种好方法是将其序列化为格式化的 JSON。例如使用 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.

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

回答by Dmitri

I often use function like this one ( it might need to be expanded to accommodate prety-print of other types of object inside of Map ).

我经常使用这样的函数(它可能需要扩展以适应 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(...)

Thus following code

因此下面的代码

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));
}

will produce output

将产生输出

[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]

Again. You may need to modify this for your particular needs.

再次。您可能需要根据您的特定需要修改它。