Commons Collection Interfaces
- Commons Collections - Bag Interface
- Commons Collections - BidiMap Interface
- Commons Collections - MapIterator Interface
- Commons Collections - OrderedMap Interface
Commons Collections Usage
- Commons Collections - Ignore Null
- Commons Collections - Merge & Sort
- Commons Collections - Transforming Objects
- Commons Collections - Filtering Objects
- Commons Collections - Safe Empty Checks
- Commons Collections - Inclusion
- Commons Collections - Intersection
- Commons Collections - Subtraction
- Commons Collections - Union
Commons Collections Resource
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