How can I count occurrences with groupBy?


I want to collect the items in a stream into a map which groups equal objects together, and maps to the number of occurrences.

List<String> list = Arrays.asList("Hello", "Hello", "World");
Map<String, Long> wordToFrequency = // what goes here?

So in this case, I would like the map to consist of these entries:

Hello -> 2
World -> 1

How can I do that?

This question is tagged with java functional-programming java-8

~ Asked on 2014-08-22 06:46:21

The Best Answer is


I think you're just looking for the overload which takes another Collector to specify what to do with each group... and then Collectors.counting() to do the counting:

import java.util.*;

class Test {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();


        Map<String, Long> counted =
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));



{Hello=2, World=1}

(There's also the possibility of using groupingByConcurrent for more efficiency. Something to bear in mind for your real code, if it would be safe in your context.)

~ Answered on 2014-08-22 06:55:51


Here is example for list of Objects

Map<String, Long> requirementCountMap =, Collectors.counting()));

~ Answered on 2018-06-29 16:45:48

Most Viewed Questions: