Member-only story

Count Occurrence of each character in String using Java 8

Gain Java Knowledge
1 min readAug 6, 2023

--

In this tutorial we will learn How to count occurrences of a character from string using java8 stream API.

First we will split string based on “” empty string value and will store into Array of string and after that we will use Arrays.Stream(-) method and convert into stream and after converting into stream we can call .collect(-) method.Inside collect(-) method we can pass the parameter Collectors.groupingBy(-,-) and Inside Collectors.groupingBy(-,-) function we can pass the two parameters one is Function.identity() to find the unique identity of each element and second parameter we can pass Collectors.counting() to count the number of occurrence for each character.

String input = "gainjavaknowledge";

String [] array = input.split("");

Map<String, Long> output = Arrays.stream(array).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CountCharacterOccurrence {

public static void main(String[] args) {
String input = "gainjavaknowledge";

Map<String, Long> output = Arrays.stream(input.split("")).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println("Output : "+output);

}
}

Watch Video Here :

--

--

Gain Java Knowledge
Gain Java Knowledge

Written by Gain Java Knowledge

The Java programming language is one of the most popular languages today. Stay up to date with news, certifications, free learning resources and much more.

No responses yet