Multi-line pretty-printing of (nested) collections in Java

左心房为你撑大大i 提交于 2019-11-29 09:56:24

You can use the method MapUtils.debugPrint from the apache commons collections in order to print nested maps.

This method prints a nicely formatted String describing the Map. Each map entry will be printed with key, value and value classname. When the value is a Map, recursive behaviour occurs.

Try replacing the start of each entry with new line and tab like this

myMap.toString().replace("[", "\n\t[");

I am not 100% sure, might be is this what you are looking for and which you called pretty printing -

Map<Integer,String> map = new HashMap<Integer,String>();
...
for(Map.Entry<Integer,String> entry: map.entrySet()){
    System.out.println(entry.getKey()+" - "+ entry.getValue());
}

I was looking for a printing of nested collections in Java which brought me here. However the answers only work for Maps therefore I thought I'd add my solution for nested Collections. It produces a JSON like output, if you want newlines add "]\n" rather than ']'.

Note that this will not produce pretty output if the Object[] contains nested elements. You would need to write a separate method to deal with nested arrays. Also it will not pretty print primitive arrays, for that you'd need an else statement for every primitive array type.

private static <A extends Collection<B>, B> String nestedToString(A collection) {
    if (collection == null)
        return "null";

    String ret = "";

    Iterator<B> colIterator = collection.iterator();
    if (colIterator.hasNext()) {
        ret += '[';
        while (colIterator.hasNext()) {
            B object = colIterator.next();
            if (object == null) {
                ret += "null";
            } else if (object instanceof Collection) {
                ret += nestedToString((Collection) object);
            } else if (object instanceof Object[]) {
                ret += Arrays.deepToString((Object[]) object);
            } else {
                ret += object;
            }
            if (colIterator.hasNext()) {
                ret += ", ";
            }
        }
        ret += ']';
    }
    return ret;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!