Learnitweb

Find the frequency of each character in a string using Java 8 streams

You can use Java 8 Streams to count the frequency of each character in a string by using the Collectors.groupingBy() collector. Here’s how:

import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CharacterFrequency {
    public static void main(String[] args) {
        String str = "hello world";

        Map<Character, Long> frequencyMap = str.chars()
                .mapToObj(c -> (char) c)  // Convert int to Character
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        System.out.println(frequencyMap);
    }
}

Output:

{ =1, r=1, d=1, e=1, h=1, l=3, o=2, w=1}

Explanation:

  • str.chars() converts the string into an IntStream of ASCII values.
  • .mapToObj(c -> (char) c) converts each ASCII value to a Character object.
  • .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) groups the characters and counts their occurrences.