How to count the frequency of words of List in Java 8?
List <String> wordsList = Lists.newArrayList("hello", "bye", "ciao", "bye", "ciao");
The result must be:
{ciao=2, hello=1, bye=2}
I want to share the solution I found because at first I expected to use map-and-reduce methods, but it was a bit different.
Map<String, Long> collect =
wordsList.stream().collect(groupingBy(Function.identity(), counting()));
Or for Integer values:
Map<String, Integer> collect =
wordsList.stream().collect(groupingBy(Function.identity(), summingInt(e -> 1)));
EDIT
I add how to sort the map by value:
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
));