Apache Commons Collections - Transforming Objects



Transforming a list of objects

collect() method of CollectionUtils can be used to transform a list of one type of objects to list of different type of objects.

Usage

List<Integer> integerList = (List<Integer>) CollectionUtils.collect(stringList,
   new Transformer<String, Integer>() {
      @Override
      public Integer transform(String input) {
         return Integer.parseInt(input);
      }
});

Declaration

Following is the declaration for

org.apache.commons.collections4.CollectionUtils.collect() method −

public static <I,O> Collection<O> collect(Iterable<I> inputCollection, Transformer<? super I,? extends O> transformer)

Parameters

  • inputCollection − The collection to get the input from, may not be null.

  • Transformer − The transformer to use, may be null.

Return Value

The transformed result (new list).

Exception

  • NullPointerException − If the input collection is null.

Example - Transforming a List of String to List of Integers

The following example shows the usage of org.apache.commons.collections4.CollectionUtils.collect() method. We'll transform a list of string to list of integer by parsing the integer value from String.

CommonCollectionsTester.java

package com.tutorialspoint;

import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Transformer;

public class CommonCollectionsTester {
   public static void main(String[] args) {
      List<String> stringList = Arrays.asList("1","2","3");
      List<Integer> integerList = (List<Integer>) CollectionUtils.collect(stringList,
         new Transformer<String, Integer>() {
      
         @Override
         public Integer transform(String input) {
            return Integer.parseInt(input);
         }
      });
      System.out.println(integerList);
   }
}

Output

When you use the code, you will get the following code −

[1, 2, 3]
Advertisements