- Commons Collections - Discussion
- Commons Collections - Useful Resources
- Commons Collections - Quick Guide
- Commons Collections - Union
- Commons Collections - Subtraction
- Commons Collections - Intersection
- Commons Collections - Inclusion
- Commons Collections - Safe Empty Checks
- Commons Collections - Filtering Objects
- Commons Collections - Transforming Objects
- Commons Collections - Merge & Sort
- Commons Collections - Ignore Null
- Commons Collections - OrderedMap Interface
- Commons Collections - MapIterator Interface
- Commons Collections - BidiMap Interface
- Commons Collections - Bag Interface
- Commons Collections - Environment Setup
- Commons Collections - Overview
- Commons Collections - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Commons Collections - Transforming Objects
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