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 TransformerCollectionUtils.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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access