How do I dump the contents of a hash map?

后端 未结 3 748
难免孤独
难免孤独 2021-01-17 11:02

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

3条回答
  •  囚心锁ツ
    2021-01-17 11:56

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

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

    Thus following code

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

    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.

提交回复
热议问题