Java Programming Tutorials

Java programming tutorials with many code examples!

Java 8 count frequency of chars in String

Java interview question: In Java 8 count frequency of chars in a String. In this post we’ll show two implementations – using Map.merge() and Streams and Collectors.

foreach with Java 8 Map.merge()

The simplest way to count frequency of chars in a String is to use the standard foreach loop for char array traversal and doing counting with fantastic Map.merge() available since Java 8:

String s = "abcaba";
Map<Character, Integer> freqs = new HashMap<>();
for (char c : s.toCharArray()) {
    freqs.merge(c,                  // key = char
                1,                  // value to merge
                Integer::sum);      // counting
}
System.out.println("Frequencies:\n" + freqs);

Isn’t that cool? :-) Map.merge(key, value, BiFunction) is doing the tedious update of the Map if a char exists there or not.

The above code prints:

Frequencies:
{a=3, b=2, c=1}

Java 8 Stream and Collector

Another approach could be using Stream of chars and using some Collector to count and store values, but the solution is a bit cumbersome due to typing:

String s = "abcaba";
Map<Character, Integer> frequencies = s.chars().boxed()
        .collect(toMap(
                // key = char
                k -> Character.valueOf((char) k.intValue()),
                v -> 1,         // 1 occurence
                Integer::sum)); // counting
System.out.println("Frequencies:\n" + frequencies);

The String.chars() method returns IntStream of characters, so we have to box them to Integer to resolve type problems in Collector.

Frequencies:
{a=3, b=2, c=1}

References:

Share with the World!