javajava-8java-streamword-count

Word frequency count Java 8


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}

Solution

  • 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( Collectors.groupingBy( Function.identity(), Collectors.counting() ));
    

    Or for Integer values:

    Map<String,Integer> collect = wordsList.stream()
         .collect( Collectors.groupingBy( Function.identity(), Collectors.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
                ));