Word frequency counting in Java 8
How to count the frequency of a word in a list using Java 8?
<code class="java">List<String> wordsList = Lists.newArrayList("hello", "bye", "ciao", "bye", "ciao");</code>
The result should be:
<code class="java">{ciao=2, hello=1, bye=2}</code>
At first, I expected to use the map and reduce method, but the actual method is slightly different.
<code class="java">Map<String, Long> collect = wordsList.stream() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));</code>
Or for integer values:
<code class="java">Map<String, Integer> collect = wordsList.stream() .collect(Collectors.groupingBy(Function.identity(), Collectors.summingInt(e -> 1)));</code>
EDIT
I also added how to sort the map by value:
<code class="java">LinkedHashMap<String, Long> countByWordSorted = collect.entrySet() .stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> { throw new IllegalStateException(); }, LinkedHashMap::new ));</code>
The above is the detailed content of How to Calculate Word Frequencies in a List Using Java 8?. For more information, please follow other related articles on the PHP Chinese website!