In this post under Apache Collections, I will show with example, how to use and purpose of “transform” static method in Apache Collections “CollectionUtils” class.
The “transform” method can be used to transform each elements in a collection.
The transformer logic is implemented by implementing the “Transformer” functional interface.
Please note it doesn’t create a new collection that will contain the transformed element, it populates the existing collection with the transformed elements.
Below is the main class showing its usage
Main class
package defaultPackage;import org.apache.commons.collections4.CollectionUtils;import java.util.ArrayList;import java.util.List;public class Example19 { public static void main(String[] args) { List<Integer> integerList = new ArrayList<>(0); integerList.add(1); integerList.add(2); integerList.add(3); integerList.add(4); CollectionUtils.transform(integerList, (input) -> { return input * 2; }); for(int data : integerList) { System.out.println(data); } }}
In the above code, at line 10, I create a list containing integers.
From line 11 to 14, I populate the list with 4 integers.
At line 16, I call “transform” method pass the integer list and “Transformer” functional interface implementation as arguments.
The “Transformer” functional interface, take each integer element from the collection and multiply it by 2.
Then at line 21, I print the collection.
In this way, we can use “CollectionUtils” static method “transform”
Below is the output
Output
2468