Pretty-print a Map in Java

前端 未结 16 1118
傲寒
傲寒 2020-12-04 10:11

I am looking for a nice way to pretty-print a Map.

map.toString() gives me: {key1=value1, key2=value2, key3=value3}

I

16条回答
  •  一整个雨季
    2020-12-04 10:36

    Or put your logic into a tidy little class.

    public class PrettyPrintingMap {
        private Map map;
    
        public PrettyPrintingMap(Map map) {
            this.map = map;
        }
    
        public String toString() {
            StringBuilder sb = new StringBuilder();
            Iterator> iter = map.entrySet().iterator();
            while (iter.hasNext()) {
                Entry entry = iter.next();
                sb.append(entry.getKey());
                sb.append('=').append('"');
                sb.append(entry.getValue());
                sb.append('"');
                if (iter.hasNext()) {
                    sb.append(',').append(' ');
                }
            }
            return sb.toString();
    
        }
    }
    

    Usage:

    Map myMap = new HashMap();
    
    System.out.println(new PrettyPrintingMap(myMap));
    

    Note: You can also put that logic into a utility method.

提交回复
热议问题