Uploaded image for project: 'Commons Collections'
  1. Commons Collections
  2. COLLECTIONS-550

Provide a simple way for creating an arbitrary String representation of a given Iterable

    XMLWordPrintableJSON

    Details

    • Type: New Feature
    • Status: Closed
    • Priority: Minor
    • Resolution: Fixed
    • Affects Version/s: 4.0
    • Fix Version/s: 4.1
    • Component/s: Collection
    • Labels:

      Description

      Create an utility method that returns an arbitrary String representation of a given Iterable, where for each Iterable element one may require a String representation that is different from the element's own toString() result.

      Additionally the client may also provide an optional delimiter, where the default one could be the common ", ".

      The transformation of each Iterable element into an arbitrary String could be implemented by the means of a Transformer.

      Example (illustrative method in CollectionUtils):

      static <C> String toString(Iterable<C> iterable, Transformer<C, String> transformer);
      

      Consider the following illustrative class:

      class SomeClass {
      
        private final String propertyOne;
        private final String propertyTwo;
      
        public SomeClass(String propertyOne, String propertyTwo) {
          this.propertyOne = propertyOne;
          this.propertyTwo = propertyTwo;
        }
      
        public String getPropertyOne() {
          return propertyOne;
        }
      
        public String getPropertyTwo() {
          return propertyTwo;
        }
      
        @Override
        public String toString() {
          return propertyOne;
        }
      
      }
      

      One could transform an Iterable containing elements of type SomeClass into a client provided String representation by calling:

      // list contains elements of type SomeClass
      String result = CollectionUtils.toString(list, new Transformer<SomeClass, String>() {
        @Override
        public String transform(SomeClass someClass) {
          return someClass.getPropertyTwo();
        }
      });
      
      // Will print "propertyTwoA, propertyTwoB"
      System.out.println(result);
      
      result = CollectionUtils.toString(list, new Transformer<SomeClass, String>() {
        @Override
        public String transform(SomeClass someClass) {
          return someClass.getPropertyOne() + someClass.getPropertyTwo();
        }
      });
      
      // Will print propertyOneApropertyTwoA, propertyOneBpropertyTwoB
      System.out.println(result);
      
      

        Attachments

          Activity

            People

            • Assignee:
              Unassigned
              Reporter:
              gonmarques Gonçalo Marques
            • Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved: