Pretty-print a Map in Java

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

    You should be able to do what you want by doing:

    System.out.println(map) for example

    As long as ALL your objects in the map have overiden the toString method you would see:
    {key1=value1, key2=value2} in a meaningfull manner

    If this is for your code, then overiding toString is a good habit and I suggest you go for that instead.

    For your example where your objects are Strings you should be fine without anything else.
    I.e. System.out.println(map) would print exactly what you need without any extra code

提交回复
热议问题