Word frequency count Java 8

Mouna picture Mouna · Mar 18, 2015 · Viewed 55.7k times · Source

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}

Answer

Mouna picture Mouna · Mar 18, 2015

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
            ));