Pretty-print a Map in Java

前端 未结 16 1192
傲寒
傲寒 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:39

    I guess something like this would be cleaner, and provide you with more flexibility with the output format (simply change template):

        String template = "%s=\"%s\",";
        StringBuilder sb = new StringBuilder();
        for (Entry e : map.entrySet()) {
            sb.append(String.format(template, e.getKey(), e.getValue()));
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1); // Ugly way to remove the last comma
        }
        return sb.toString();
    

    I know having to remove the last comma is ugly, but I think it's cleaner than alternatives like the one in this solution or manually using an iterator.

提交回复
热议问题