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
));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…