In this post under Apache Collections, I will explain with example the purpose of “collect” static method in “CollectionUtils” class.
The “collect” method takes a list of items, process or transform them and then create a new list containing transformed items.
Below is an Main example showing its usage.
Main class
1 package defaultPackage;
2
3 import org.apache.commons.collections4.CollectionUtils;
4
5 import java.util.ArrayList;
6 import java.util.List;
7
8 public class Example8 {
9 public static void main(String[] args) {
10 List<Integer> intList = new ArrayList<Integer>();
11 intList.add(1);
12 intList.add(2);
13 intList.add(3);
14 intList.add(4);
15 intList.add(5);
16
17 List<String> stringList = new ArrayList<String>();
18
19 CollectionUtils.collect(intList, (Integer item) -> { item = item + 20; return item.toString(); },stringList);
20
21 for(String data : stringList) {
22 System.out.print(data + ",");
23 }
24 }
25 }
In the above main code, I created an empty list of type Integer, refer to line 10.
Then from line 11 to 15, I populate it with integer values.
At line 17, I created another empty list of type String.
At line 19, I called the static method “collect” passing three arguments
1) the input list which in this case is “intList”
2) the transformation logic that has to be performed on each item of input list. I am using lambda here
3) the destination list which in this case is “stringList”
After this method call, the “stringList” which was empty earlier is populated with transformed elements of type String.
Next I loop through the elements and print them.
In this way, I can use “CollectionUtils” “collect” method.