5.16. Transforming Collections

Problem

You need to perform a transformation using each element in a Collection.

Solution

Use CollectionUtils.transform() . Supply a Collection and a Transformer to this method, and this utility will pass each element in the Collection to that Transformer, returning a new Collection containing the results of each transformation. The following example demonstrates the use of transform( ) with a custom Transformer object:

import java.util.*;
import org.apache.commons.collections.Transformer;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

// Create a transformer that reverses strings.
               Transformer reversingTransformer = new Transformer( ) {
                   public Object transform(Object object) {
                       String string = (String) object;
                       return StringUtils.reverse( string );
                   }
               }

String[] array = new String[] { "Aznar", "Blair", "Chirac", "Putin", "Bush" };
List stringList = Arrays.asList( ArrayUtils.clone( array ) );

// Transform each element with a Transformer
               CollectionUtils.transform( stringList, reversingTransformer );

System.out.println( "Original: " + ArrayUtils.toString( array ) );
System.out.println( "Transformed: " + 
                    ArrayUtils.toString( stringList.toArray( ) ) );

This example creates a List of strings, transforming each element with a Transformer that produces reversed strings. The List is transformed in-place, which means that the contents of the List are replaced with the ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.