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

5

9

I want to be able to (pretty-)print the contents of my maps.

They should have newlines and indentation rather than on a single line; ignoring the toString methods of collections/iterables/etc; and recursing into nested collections.

This is especially of interest for me regarding maps. I suppose JSON'ing might be relevant, but I don't want to go that far, or at least - I don't want my code to have to know about JSON just for me to pretty-print it. What are my options (other than writing this myself)?

Incitement answered 2/3, 2013 at 6:50 Comment(0)
R
15

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.

Reconstructionist answered 3/3, 2013 at 23:22 Comment(2)
link is not working, try this - commons.apache.org/proper/commons-collections/javadocs/…Calorifacient
@Calorifacient I have updated the link. Note that you linked to the 2.1.1 version, while there is a 3.2.1 version as well. (The 4.0 is still alpha)Reconstructionist
G
4

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

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

Goggler answered 2/3, 2013 at 6:56 Comment(1)
This approach lacks of proper identation by spaces.By
D
1

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());
}
Detribalize answered 2/3, 2013 at 6:55 Comment(2)
This doesn't do indentation and doesn't help me with nested maps (or other collections).Incitement
Its just a iteration over a single map. In case you have nested collection you could use nested loop inside it.Detribalize
C
1

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;
}
Cadent answered 11/5, 2017 at 7:32 Comment(0)
F
0

I know OP specified no JSON solution, but I found doing this was very lightweight and perfect for my requirements:

    Gson gson = new GsonBuilder().setPrettyPrinting().create();     
    System.out.println(gson.toJson(myMap).replaceAll("\"","")); // Get rid of annoying "
Foreyard answered 26/5, 2024 at 9:7 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.