×

Java program to count the occurrences of each character

The count of each character is the frequency of the characters. For example, the given String is “Programming”. In the given string, the count of the characters ‘P’ -1, ’r’-2, ‘o’ -1, ‘g’-2, ‘a’-1,’m’-2, ‘I’-1, ’n’-1. There are different methods for finding the character's cout.

Several ways to determine how frequently each character appears. Examples of them include:

  • By using the Counter Array
  • By Java HashMap
  • By using a Naive Approach
  • By using the Java8

1. By usinga Naive Approach

It is one of the simplest methods for finding the occurrence of a character.

Example: CountOOfChar1.java

// this program is for finding the count of each character
//importing the required packages
import java.io.*;
import java.util.*;
// A class CountOOfChar1 is created
public class CountOOfChar1  
{  
static final int MAX_CHAR = 256;  
static void getOccuringChars(String st)  
{  
// an array was created with the size of 256 ( Ascii values)  
int counts[] = new int[MAX_CHAR];  
// a variable for finding the length of the String given as input 
int length = st.length();  
// the index value of the count array is initialized
for (int i = 0; i < length; i++)  
counts[st.charAt(i)]++;  
// an array which has the size as the length of the String is created  
char cha[] = new char[st.length()];  
for (int i = 0; i < length; i++)   
{  
cha[i] = st.charAt(i);  
int finds = 0;  
for (int j = 0; j <= i; j++)   
{  
// if the condition becomes true as the ame character is found 
if (st.charAt(i) == cha[j])  
finds++;  
}             
if (finds == 1)  
// display the character count  
System.out.println("The count of the "+ st.charAt(i)+ " is: " + counts[st.charAt(i)]);  
}  
}  
// main section of the program  
public static void main(String args[])  
{  
String st = "Preciouspeoplearedangerious"; // a string
//function calling 
getOccuringChars(st);  
}  
} 

Output

The count of the character P is: 1
The count of the character r is: 3
The count of the character e is: 5
The count of the character c is: 1
The count of the character i is: 2
The count of the character o is: 3
The count of the character u is: 2
The count of the character s is: 2
The count of the character p is: 2
The count of the character l is: 1
The count of the character a is: 2
The count of the character d is: 1
The count of the character n is: 1
The count of the character g is: 1

2. By using the Counter Array

The counter arrays are utilized in the following Java program to count the instances of each letter in a text. The count variable is increased by 1 at each character-based index by that of the for loop, which iterates across the provided String. If counter[i] is not 0, repeat the process and print the characters and frequency.

Example:CountOfChar1.java

// this program is for finding the count of each character
//importing the required packages
import java.io.*;
import java.util.*;
import java.util.Scanner;  
public class CountOfChar1  
{  
public static void main(String args[])   
{  
String st;  
int i, length;  
int counters[] = new int[256];  
Scanner sc = new Scanner(System.in);  
System.out.print(" Enter the String : ");  
// the input is read from the user
st = sc.nextLine();  
// the method for finding the length of the given String  
length= st.length();  
// loop through all the String, measure how often each character appears, and save the results in a counting array.
for (i = 0; i < length; i++)   
{  
counters[(int) st.charAt(i)]++;  
}  
// display the count of the characters
for (i = 0; i < 256; i++)   
{  
if (counters[i] != 0)   
{  
//  display the count of the characters    
System.out.println((char) i + " ------> " + counters[i]);  
}  
}  
}  
}  

Output

Enter the String: prashantdesghj 
a ------> 2
d ------> 1
e ------> 1
g ------> 1
h ------> 2
j ------> 1
n ------> 1
p ------> 1
r ------> 1
s ------> 2
t ------> 1

By use of Java HashMap

Characters are a key in the program, and their occurrence is used as a value. To count the number of times each character appears in the provided String, we utilized Java HashMap inside the next Java application. Since the duplicated key is not stored in the hashmap, we know it only holds key and value pairs.

We first turned the provided String into a character array to iterate through the characters array. In the HashMap, change the count. Afterward, we must determine whether or not a key for every character currently exists in the hash map. If it already exists, raise the count variable; otherwise, add it as a new key to the Map and supply the starting value using the count.

Example: CountOfChar2.java

// this program is for finding the count of each character
//importing the required packages
import java.io.*;
import java.util.*;
import java.util.Scanner;  
import java.util.HashMap;     
public class CountOfChar2  
{  
public static void main(String args[])   
{  
String st = "Websites";  
//With char as the key and frequency as the value in a hashing map.
HashMap <Character, Integer> charCounts = new HashMap<>();  
for (int i = st.length() - 1; i >= 0; i--)   
{  
if(charCounts.containsKey(st.charAt(i)))   
{  
int counts = charCounts.get(st.charAt(i));  
charCounts.put(st.charAt(i), ++counts);  
}   
else   
{  
charCounts.put(st.charAt(i),1);  
}  
}  
System.out.println(charCounts);  
}  
}

 Output

{b=1, s=2, t=1, e=2, W=1, I=1}

By using Java 8

We have included Java 8 capabilities in the following Java application. The String whose occurrences of the characters are to be collected has first been started. Following that, we produced a Java Map object. To obtain the character's frequency, we carried out several intermediary processes.

The String.Split () function is first used to divide the supplied text into an array. Afterward when the supplied collection is returned as a stream using the Arrays. stream() function.

The String is changed into lower characters in the next intermediate process. To accomplish this, we utilized using Stream. Map () function, which creates a stream from the components in the streaming after performing the particular function on them.

The list members are concatenated, and a temporary reduction procedure is carried out using the collect() method. A Collector that implements a cascaded "group by" action on input items of type T is returned by the Collectors. grouping() function.

We used the Collectors object's counting() function to count all items. The procedure returns a Collector accepting items of type T. If there are no input items, it returns 0. Otherwise, it counts the number of input items.

Example: CountOfChar3.java

// this program is for finding the count of each character
//importing the required packages
import java.io.*;
import java.util.*;
import java.util.Scanner;  
import java.util.HashMap;     
import java.util.stream.Collectors;  
import java.util.*;  
public class CountOfChar3  
{  
public static void main(String args[])   
{  
//declaring the string input
String st= "primefactors";  
Map<String, Long> results = Arrays.stream(st.split("")).map(String::toLowerCase).collect(Collectors.groupingBy(s -> s, LinkedHashMap::new, Collectors.counting()));  
//displaying the result
System.out.println(results);  
}  
}  

Output

{p=1, r=2, i=1, m=1, e=1, f=1, a=1, c=1, t=1, o=1, s=1}

The concept of the Java program that comes after is similar to the program above, with a few exceptions. We utilized the Java Patterns class inside the following Java application.

The compile() function, which converts the provided mathematical equation into the pattern, has been called first. We then invoked the method matcher() to build a matching technique (match the given input against this pattern).

The items kept inside the Map have finally been counted in the items of the Map. Use the affecting approximately() loop to run across the Map after the count. The situation applies to Java 8 or higher versions.

Example: CountOfChar4.java

// this program is for finding the count of each character
//importing the required packages
import java.io.*;
import java.util.*;
import java.util.Scanner;  
import java.util.HashMap;     
import java.util.stream.Collectors;  
import java.util.stream.Collectors;  
import java.util.*;  
import java.util.regex.Pattern;  
public class CountOfChar4   
{  
public static void main(String args[])   
{  
String st = "Programming";  
Pattern.compile(".").matcher(st).results().map(m -> m.group().toLowerCase()).collect(Collectors.groupingBy(s -> s, LinkedHashMap::new, Collectors.counting())).forEach((k, v) -> System.out.println(k + " repeated " + v + " times"));   
}  
}  

Output

p repeated 1 time
r repeated 2 times
o repeated 1 times
g repeated 2 times
a repeated 1 times
m repeated 2 times
i repeated 1 times
n repeated 1 times

Related Topics

Nested Enum in Java

A class that can be defined within another class is called a nested class in Java. You can logically group classes that are used onlyin one place. This makes encapsulation...

3 minutes read.

POJO in Java

Plain old Java Object, in short, is called POJO in Java. POJO is an everyday object that is not subject to any specific limitations. We can use POJO in any Java...

3 minutes read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.

Anagram Program in Java using String

Anagram Program in Java Anagrams are those words that are generated by rearrangement of the letters of another phrase or word. Usually, while doing the rearrangement, the original letters are used...

8 minutes read.

Read the XLSX file in Java

Excel files contain cells; reading an excel file in Java differs from reading a word file. JDK doesn't have a direct API that can read or write Word or Excel...

3 minutes read.

Singleton class in Java

What is Singleton class in Java? Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class...

3 minutes read.

Types of JDBC Drivers

JDBC Drivers: A piece of software known as JDBC Driver permits database communication between Java applications and the server. In order to communicate with our database server, JDBC drivers put into practice...

4 minutes read.

Difference between String and Char Array in Java

We are heading to examine some significant differences between String and Character arrays. Both char arrays and String hold the series of characters and are utilised as a cluster of...

3 minutes read.

LCM Program in Java

LCM Program in Java The LCM program in Java outputs the LCM of the given numbers. In Arithmetic, the lowest common multiple, least common multiple or smallest common multiple of the...

6 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Java Variable

The variable is the basic unit of storage in a program. We define a variable using an identifier, a type, and an optional initializer in Java. In Java, variables must be...

4 minutes read.

Static vs Non-Static in Java

A static method can access and update the value of a static data member. The static keyword is mostly used in Java for memory management. The static keyword can be...

6 minutes read.

Star Program in Java

By solving the patterns, we can develop our coding skills and logical thinking. Mostly each pattern program uses two or more loops. Loops' number depends on the complexity of logic....

3 minutes read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

What is advance Java?

The definition of advance inside the dictionary refers to a forward motion, development, or progress, and the definition of enhancing is something that improves things. To become experts in that...

3 minutes read.

Java String isEmpty() method

Java String isEmpty() method checks whether current String is empty or not. Syntax: public boolean isEmpty() Returns It returns true, if length of String is 0 otherwise false. Java String isEmpty() method example 1    ...

1 minute read.

Command Class in Java

We use the command class to run commands against the database. The Command class may find a set of parameter objects for use in sending values to a stored procedure...

3 minutes read.

How to Create a Generic List in Java?

Generics are types that have parameters. The goal is to make it possible for methods, classes, and interfaces to take type (Integer, String, etc., and user-defined types) as a parameter....

4 minutes read.

Classes and Objects in Java Example Programs

Classes and Objects in Java Example Programs Java is an Object-Oriented programming language, i.e., everything in Java is associated with objects and objects are associated with classes. The classes and objects...

5 minutes read.

Java Print Writer

PrintWriter: It is used to write output data from the file. It is the class of Java.io package. It inherits the properties of the Writer class. Writer Class: It is a class of...

4 minutes read.