Various Ways to Get the Number of Occurrences for Elements in a List

In this article, let’s find the various ways to get the number of occurrences of elements in a Java List.

Using Collections.frequency()

When you want to get the number of occurrences for only one specific element, just use Collections.frequency.

It is a JRE built-in method and was introduced since JDK1.5.

        List<String> list = Lists.newArrayList("a", "a", "b");
        Assertions.assertEquals(2, Collections.frequency(list, "a"));

Using a Map

        List<String> list = Lists.newArrayList("a", "a", "b");
        Map<String, Integer> countMap = Maps.newHashMap();
        for (String s : list) {
            if (countMap.containsKey(s)) {
                countMap.put(s, countMap.get(s) + 1);
            } else {
                countMap.put(s, 1);
            }
        }
// Or
//        list.forEach(
//                e -> countMap.put(e, countMap.getOrDefault(e, 1) + 1)
//        );

// Or
//        list.forEach(e-> countMap.merge(e, 1, Integer::sum));

        Assertions.assertEquals(2, countMap.get("a"));

Using Java 8 Stream with Map

        List<String> list = Lists.newArrayList("a", "a", "b");
        Map<String, Long> countMap =
                list.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()));

        Assertions.assertEquals(2, countMap.get("a"));

Using Google Guava Multiset

If you have Google Guava library in your classpath, you can also use Multiset. You can check the Read More section for detail.

        List<String> list = Lists.newArrayList("a", "a", "b");
        Multiset<String> multiset = HashMultiset.create(list);

        Assertions.assertEquals(2, multiset.count("a"));

Read More