How to count occurrences with Java 8 streams?

Question:

I am passing an app from Java6 to , there are cases in which we have to count the occurrences of a String in a list. For this we use:

Collections.frequency(lista, stringALocalizar);

I think this part should not be touched. If, instead, we have to count all the String and their occurrences through the entire list we have to iterate over the list and use a HashMap<String, Integer> to store the results and not perform the extra iterations that Collections.frequency would cause . Something like this:

for (String stringALocalizar : lista) {
    if (mapaDeResultados.containsKey(stringALocalizar)) {
        mapaDeResultados.put(stringALocalizar, mapaDeResultados.get(stringALocalizar)+1);
    } else {
        mapaDeResultados.put(stringALocalizar, 1);
    }
 }

How can I get the same result with streams?

Answer:

You can use

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

What it does is group the elements of the list and count the occurrences, Function.identity() indicates that the grouping is for each different chain in the list and Collectors.Counting() returns a Collector that counts the elements of the stream, this object returns the count in a variable of type Long so the map is declared as Map<String, Long> .

Scroll to Top