Java printf functionality for collections or arrays


In python you can use a tuple in a formatted print statement and the tuple values are used at the indicated positions in the formatted string. For example:

>>> a = (1,"Hello",7.2)
>>> print "these are the values %d, %s, %f" % a
these are the values 1, Hello, 7.200000

Is there some way to use any array or collection in a java printf statement in a similar way?

I've looked at the documentation and it appears to have built in support for some types like Calendar, but I don't see anything for collections.

If this isn't provided in java, is there any java idiom that would be used in a case like this where you are populating collections and then printing the values from many collections using one format string (other than just nested looping)?

Best Solution

printf will have a declaration along the lines of:

public PrintString printf(String format, Object... args);

... means much the same as []. The difference is ... allows the caller to omit explicitly creating an array. So consider:

    out.printf("%s:%s", a, b);

That is the equivalent of:

    out.printf("%s:%s", new Object[] { a, b });

So, getting back to your question, for an array, you can just write:

    out.printf("%s:%s", things);

For a collection:

    out.printf("%s:%s", things.toArray());