English 中文(简体)
Commons Collections - Transforming Objects
  • 时间:2024-09-17

Commons Collections - Transforming Objects


Previous Page Next Page  

CollectionUtils class of Apache Commons Collections pbrary provides various utipty methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This pbrary is very useful prior to jdk 8 as similar functionapties are now provided in Java 8 s Stream API.

Transforming a pst

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

Declaration

Following is the declaration for

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


pubpc 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 pst).

Exception

    NullPointerException − If the input collection is null.

Example

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


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

pubpc class CollectionUtilsTester {
   pubpc 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
         pubpc 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