Java Program to Find Maximum Occurring Character in a String

In this section, we will show you how to find maximum occurring character in a string.

1. Using For loop and Map

2. Using For loop

3. Using Java 9 chars() method

4. Using Java 8 Streams

Example 1. Using For loop and Map

Note: We may have more than one character with the same maximum occurence. This program will print all the character with maximum occurence. 
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class Main {

public static void main(String[] args) {

String string = "java awesome dude";

char chars[] = string.toCharArray();

Map<Character, Integer> occurrences = new HashMap<>();

for ( Character character : chars ) {

Integer oldCount = occurrences.get(character);
if ( oldCount == null ) {
oldCount = 0;
}
occurrences.put(character, oldCount + 1);
}

int maxValue =(Collections.max(occurrences.values()));

for (Map.Entry<Character, Integer> entry : occurrences.entrySet()) {

if (entry.getValue()==maxValue) {
System.out.println(entry.getKey());
}
}
}
}

First, declare the input String.

Using toCharArray() method convert String to char Array.

HashMap is used to store character and their occurence count.

Iterate over String array and put Character and occurence count inside HashMap.

Find maximum value in the HashMap using max() method.

Iterate over HashMap.

Finally, print the characters with maximum value.

Console Output: 

a

e


Example 2. Using For loop

public class Main {

public static void main(String[] args) {

String string = "javaawesome";

char chars[] = string.toCharArray();
int maximumFrequency = 0;
Character mostRepeatedChar = null;

for (int i = 0; i < chars.length; i++) {
Character temp = chars[i];
int count = 1;
for (int j = i + 1; j < chars.length; j++) {
if (temp.equals(chars[j]))
count++;
}
if (maximumFrequency < count) {
maximumFrequency = count;
mostRepeatedChar = temp;
}
}
System.out.println(mostRepeatedChar);
}
}

Declare the String.

Convert String to char array using toCharArray() method.

Here we declared maximumFrequency = o and mostRepeatedChar = null, based on condition these values will change.

Loop through array. Declared temp element whose value is chars[i]. Declared count equal to one.

Then, Loop through array. Check whether temp element is equal to chars[j]. If both are equal increment count.

Finally check whether count is greater than maximumFrequency. If so, maximumFrequency = count and mostRepeatedChar  = temp.

Console Output: 

a


Example 3. Using Java 9 chars() method

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {

public static void main(String[] args) {

String string = "javaawesome";

Character mostRepeatedChar = string.chars()
.mapToObj(i -> (char) i)
.collect(Collectors.toMap(k -> k, v -> 1,
(a, b) -> a + 1))
.entrySet().stream().max(Map.Entry.comparingByValue())
.get()
.getKey();
System.out.println(mostRepeatedChar);
}
}

chars() returns an IntStream that consists of the code point values of the characters in the given string. This method was integrated to the String class in Java 9. 

mapToObj() is an intermediate operation, it is a method of IntStream interface is used to return an object-valued stream.

collect() method collects all objects from a stream object and stored in the Map.

entrySet() returns a set view of all the entries from the Map.

max() returns the maximum element of this stream according to the provided Comparator.

comparingByValue() method returns a comparator that compares Map.Entry in natural order on value.


Example 4. Using Java 8 Streams

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {

public static void main(String[] args) {

String string = "javaawesome";

Character mostRepeatedChar = Arrays.stream(string.split(""))
.map(o ->o.charAt(0))
.collect(Collectors.toMap(k -> k, v -> 1,
(a, b) -> a + 1))
.entrySet().stream().max(Map.Entry.comparingByValue())
.get()
.getKey();
System.out.println(mostRepeatedChar);
}
}

stream() method accepts a mandatory parameter array which is the array of whose elements are to be converted into a sequential stream and returns a Sequential Stream from the array passed as the parameter.

Split String using split() method, returns String Array.

map() method is used to convert Stream of String to Stream of Character.

collect() method collects all objects from a stream object and stored in the Map.

entrySet() returns a set view of all the entries from the Map.

max() returns the maximum element of this stream according to the provided Comparator.

comparingByValue() method returns a comparator that compares Map.Entry in natural order on value.

Console Output: 

a

More related topics,

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete