In this post under Apache Collections, I will explain with example, the purpose of CollectionUtils “getCardinalityMap” method.
This method takes a collection as an argument and returns a map.
A map where key is an element from the collection, and value will be the number of times the element is repeated in the collection.
So if a list contain below elements.
1
2
2
3
3
3
The output will be a map with below contents
Key --> Value
1 --> 1
2 --> 2
3 --> 3
In this way CollectionUtils “getCardinalityMap” is used.
Below is the complete main code for your reference
Main class
package defaultPackage;
import org.apache.commons.collections4.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Example11 {
public static void main(String[] args) {
List<Integer> intList = new ArrayList<>(0);
intList.add(1);
intList.add(2);
intList.add(2);
intList.add(3);
intList.add(3);
intList.add(3);
Map<Integer, Integer> cardinalityMap = CollectionUtils.getCardinalityMap(intList);
for(Map.Entry<Integer, Integer> entry : cardinalityMap.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
}