JDK-6538167 : (coll) Please add Collections.toString(Collection collection, String separator)
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 6
  • Priority: P5
  • Status: Closed
  • Resolution: Won't Fix
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2007-03-23
  • Updated: 2012-10-08
  • Resolved: 2010-12-24
Related Reports
Relates :  
Description
A DESCRIPTION OF THE REQUEST :
  Today there is only one simple way to convert any collection to string representation: AbstractCollection.toString() method. This method uses ", " string to separate elements.

Unfortunately, it is not often case when a collection (set or list) contains only 3-4 elements and toString() method for these elements returns very short strings. As a result, the string returned by AbstractCollection.toString() is usually long or even very long.

Converting collections to string is very useful for debugging and logging goals. But it would be very good if there would be a version of toString method allowing to specify the separator inserted between elements. If a collection contains at least several tens or hundreds elements, or if toString() returns detailed result for every element, the line separator looks much better for logging such collection or printing it on the console.

So, I offer to include the following method into standard java.util.Collections class:
public static String toString(Collection collection, String separator);
This method should work as collection.toString(), but should use the given separator instead ", " string. (Such a method cannot be added into Collection or List interface due to compatibility issues.)

Possible usage example:

List<Circle> list = ...; // list of 20-30 instances of my Circle class
logger.fine(String.format("Circles:%n    " + Collections.toString(list, String.format("%n    ")));

This code should log the text alike the following:

Circles:
    x=10, y=10, r=15
    x=20, y=10, r=10
    ...

The analogous methods may be added into java.util.Arrays class, in addition to already included Arrays.toString(...) methods.


JUSTIFICATION :
  Programming debugging or logging code often requires to build readable string representation of middle-size collections (tens or hundreds elements), but standard toString() method usually returns very long and unreadable string. It is very often task, and I think the solution could be added into standard java.util.Collections class.


CUSTOMER SUBMITTED WORKAROUND :
Almost any my package contains required package-private method :)

Comments
EVALUATION I am not convinced the proposed method would pull its weight. The convenience is very small, and the number of possible ways to pretty-print something is large. See 5015163: (str) String merge/join that is the inverse of String.split()
23-03-2007