Pretty-print a Map in Java

前端 未结 16 932
傲寒
傲寒 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:20
    Arrays.toString(map.entrySet().toArray())
    
    0 讨论(0)
  • 2020-12-04 10:21

    String result = objectMapper.writeValueAsString(map) - as simple as this!

    Result:

    {"2019-07-04T03:00":1,"2019-07-04T04:00":1,"2019-07-04T01:00":1,"2019-07-04T02:00":1,"2019-07-04T13:00":1,"2019-07-04T06:00":1 ...}
    

    P.S. add Jackson JSON to your classpath.

    0 讨论(0)
  • 2020-12-04 10:23

    Simple and easy. Welcome to the JSON world. Using Google's Gson:

    new Gson().toJson(map)
    

    Example of map with 3 keys:

    {"array":[null,"Some string"],"just string":"Yo","number":999}
    
    0 讨论(0)
  • 2020-12-04 10:24

    When I have org.json.JSONObject in the classpath, I do:

    Map<String, Object> stats = ...;
    System.out.println(new JSONObject(stats).toString(2));
    

    (this beautifully indents lists, sets and maps which may be nested)

    0 讨论(0)
  • 2020-12-04 10:24

    Since java 8 there is easy way to do it with Lambda:

    yourMap.keySet().forEach(key -> {
        Object obj = yourMap.get(key);
        System.out.println( obj);
    }
    
    0 讨论(0)
  • 2020-12-04 10:26
    public void printMapV2 (Map <?, ?> map) {
        StringBuilder sb = new StringBuilder(128);
        sb.append("{");
        for (Map.Entry<?,?> entry : map.entrySet()) {
            if (sb.length()>1) {
                sb.append(", ");
            }
            sb.append(entry.getKey()).append("=").append(entry.getValue());
        }
        sb.append("}");
        System.out.println(sb);
    }
    
    0 讨论(0)
提交回复
热议问题