×

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

Java Localization

Internationalization is the process of creating a software application that can be translated into different languages and regions without modifying the application. Creating a locale-specific application raises the cost of...

3 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 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 Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

Ternary Operator in Java

In some cases, the if...else expression in Java can be replaced by a ternary operator. Visit the Java if...else statement first before learning about the ternary operator. Ternary operator in Java A...

3 minutes read.

JDBC Architecture

JDBC: JDBC stands for Java Database Connectivity. Sun Microsystems has a specification called JDBC. JDBC is a Java API (Application Programming Interface) that enables users to interact or communicate with...

4 minutes read.

Jagged Array in Java

Prerequisite We must first understand what Arrays are and Multi-dimensional Arrays are before we can learn about Jagged arrays. Java Arrays: A collection of data types that are similar is called an...

5 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

Thread States in Java

An Item's Life Cycle (Thread States) A thread can be in any of the states mentioned above at any given time in Java. They are as follows: New Active I'm blocked or waiting Temporary...

3 minutes read.

nth Prime Number in Java

A number is considered prime if only divisible by one and itself. Prime numbers include, for example, 2, 3, 5, 7, 11, etc. In looking at it another way, a...

5 minutes read.

Pancake Sorting in Java

In the pancake sorting method, the array must be sorted using just one operation, which is: Flip the arrays arr at index 0 to index j by using flipArr(arr, h). Other sorting...

3 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

Java Integer numberOfTrailingZeros() method

The numberOfTrailingZeros()  method of Java Integer class returns the total number of zero bits following the lowest-order one-bit in the 2’s complement binary representation of the specified int value. Syntax public static...

1 minute read.

Java BLOB

The two data types used in Java to store binary and big-character objects are BLOB and CLOB. In contrast to other types of data like float, int, double, etc., it...

4 minutes read.

Convert JSON to Map in Java

JACKSON and GSON libraries are two extremely capable JSON-related libraries offered by Java. To efficiently work with the returned JSON data, we frequently need to convert JSON responses into a...

6 minutes read.

Difference between print() and println() in Java

In this tutorial, we will discuss the differences between print and println in Java language. There are mainly two methods to display the text on the console printprintln The above two methods are...

4 minutes read.

How to Solve the Deprecated Error in Java?

Deprecated Java methods should not be used because they are deprecated (often, there are better, more modern alternatives). API update. Until now, Java has kept everything backward compatible and never...

3 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.

Java.net.SocketException

Exception The problem occurred during the execution of the program. If an exception occurs in the program, the program gets terminated. To skip the exception occurring statements, we have to handle...

4 minutes read.