Introduction
In this guide, we will explore how to find the maximum occurring character in a string using both traditional methods and Java 8 Streams.
Problem Statement
The task is to create a Java program that:
- Accepts a string as input.
- Finds the character that occurs the most frequently in the string.
- Outputs the character and its frequency.
Example 1:
- Input:
"hello world"
- Output:
Character: 'l', Frequency: 3
Example 2:
- Input:
"Java programming"
- Output:
Character: 'a', Frequency: 3
Solution Steps
- Input String: Start with a string that can either be hardcoded or provided by the user.
- Count Character Occurrences (Traditional Approach): Use a
HashMap
to count the frequency of each character. - Find Maximum Occurring Character (Traditional Approach): Traverse the map to find the character with the highest frequency.
- Count Character Occurrences (Java 8 Streams): Use the Stream API to count character occurrences and find the maximum occurring character in a single pass.
- Display the Result: Print the character with its frequency.
Java Program
Traditional Approach: Find Maximum Occurring Character in a String
import java.util.HashMap;
import java.util.Map;
/**
* Traditional Approach: Find Maximum Occurring Character in a String
* Author: https://www.rameshfadatare.com/
*/
public class MaxOccurringCharTraditional {
public static void main(String[] args) {
// Step 1: Take input string
String input = "hello world";
// Step 2: Find maximum occurring character using traditional approach
Map.Entry<Character, Integer> result = findMaxOccurringCharTraditional(input);
// Step 3: Display the result
System.out.println("Character: '" + result.getKey() + "', Frequency: " + result.getValue());
}
// Method to find the maximum occurring character in a string (traditional approach)
public static Map.Entry<Character, Integer> findMaxOccurringCharTraditional(String str) {
Map<Character, Integer> frequencyMap = new HashMap<>();
for (char c : str.toCharArray()) {
frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1);
}
Map.Entry<Character, Integer> maxEntry = null;
for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) {
if (maxEntry == null || entry.getValue() > maxEntry.getValue()) {
maxEntry = entry;
}
}
return maxEntry;
}
}
Java 8 Approach: Find Maximum Occurring Character in a String
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Java 8: Find Maximum Occurring Character in a String
* Author: https://www.rameshfadatare.com/
*/
public class MaxOccurringCharJava8 {
public static void main(String[] args) {
// Step 1: Take input string
String input = "Java programming";
// Step 2: Find maximum occurring character using Java 8 Streams
Map.Entry<Character, Long> result = findMaxOccurringCharJava8(input);
// Step 3: Display the result
System.out.println("Character: '" + result.getKey() + "', Frequency: " + result.getValue());
}
// Method to find the maximum occurring character in a string (Java 8 Streams approach)
public static Map.Entry<Character, Long> findMaxOccurringCharJava8(String str) {
return str.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.max(Map.Entry.comparingByValue())
.orElseThrow();
}
}
Explanation of the Programs
- Traditional Approach: The first program uses a
HashMap
to store the frequency of each character in the string. ThegetOrDefault
method is used to increment the frequency count. After building the frequency map, the program iterates through the entries to find the character with the highest frequency. - Java 8 Approach: The second program uses the Stream API to process the string. The
chars()
method converts the string into anIntStream
of character codes, which are then converted toCharacter
objects. ThegroupingBy
collector counts the occurrences of each character, andmax(Map.Entry.comparingByValue())
finds the entry with the highest count.
Output Example
For both methods, the output will be:
Example 1:
Input: hello world
Output: Character: 'l', Frequency: 3
Example 2:
Input: Java programming
Output: Character: 'a', Frequency: 3
Advanced Considerations
- Handling Multiple Maximums: If there are multiple characters with the same maximum frequency, the methods will return the first one encountered. This behavior is consistent in both approaches.
- Case Sensitivity: The programs treat uppercase and lowercase characters as distinct (e.g., ‘a’ and ‘A’). If you want case-insensitive behavior, you can convert the string to lowercase before processing.
- Performance Considerations: Both methods are efficient for typical string lengths. The Java 8 approach is more concise and leverages modern Java features, making it a preferred choice in contemporary codebases.
Conclusion
This guide provides two methods for finding the maximum occurring character in a string: the traditional approach using a HashMap
and a more modern approach using Java 8 Streams. Both methods are effective, but the Java 8 approach offers a more functional and concise solution. Depending on your needs and the style of your codebase, either method can be used to achieve the desired result.