I'm passing an app Java6
to java-8 , there are cases where 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 String
and their occurrences across 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 would cause Collections.frequency
. 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 achieve the same result with java-8 streams ?
You can use
What it does is group the elements of the list and count the occurrences,
Function.identity()
it indicates that the grouping is for each different string in the list andCollectors.Counting()
returns oneCollector
that counts the elements of the stream, this object returns the count in a type variableLong
that is why it is declare the map asMap<String, Long>
.