There are many ways to count the number of occurrences of a character in a String in Java. In this article, we’re going to see how we can check frequency of characters inside a string by using Java Stream API.
public Map<String, Long> countChars(String input) { Map<String, Long> frequentChars = Arrays.stream(input.toLowerCase().split("")) .collect(Collectors.groupingBy(c -> c, Collectors.counting())); frequentChars.forEach((k, v) -> System.out.println(k + ":" + v)); return frequentChars; }
Here, I have converted the input string to lower case and split it into an array and then created a stream from the string array of characters from the input string converting it to lower case and then applied the Collectors.counting()
method inside the Stream.collect()
to convert it to a Map<String, Long>
where keys contain the characters and the values contain the frequency of it in the input string.
Collectors
is an implementations of Collector
that implement various useful reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria, etc. Collectors.counting()
returns a Collector
accepting elements of type T
that counts the number of input elements.
Leave a Reply