Whether you're prepping for a coding interview or cleaning messy data, identifying character repetition in a string is a classic challenge—and HashMap makes it surprisingly elegant in Java. In this blog, we’ll walk through the step-by-step logic, code, and a few clever tricks to help you nail it.
๐ง Why Use a HashMap?
It offers constant-time lookup for keys.
Helps track frequency efficiently without manual looping.
Ideal for character counting in strings.
✍️ The Problem
Given a string like "JavaProgramming", we want to:
Count how many times each character occurs.
Identify which characters repeat.
⚙️ The Plan
Convert the string to a character array.
Use a HashMap<Character, Integer> to store character frequencies.
Loop through the map to find characters with count > 1.
๐ Java Code Example
import java.util.HashMap;
public class RepeatingCharacters {
public static void main(String[] args) {
String input = "JavaProgramming";
findRepeatingCharacters(input);
}
public static void findRepeatingCharacters(String str) {
HashMap<Character, Integer> charCountMap = new HashMap<>();
// Step 1: Populate map with character frequencies
for (char c : str.toCharArray()) {
c = Character.toLowerCase(c); // optional: handle case insensitivity
charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
}
// Step 2: Print characters with count > 1
System.out.println("Repeating characters in the string:");
for (char c : charCountMap.keySet()) {
if (charCountMap.get(c) > 1) {
System.out.println(c + " occurs " + charCountMap.get(c) + " times");
}
}
}
}
๐งช Output Example
For input "JavaProgramming", you'd get something like:
a occurs 3 times
g occurs 2 times
r occurs 2 times
m occurs 2 times
๐งฉ Tips and Tricks
Want to ignore spaces and punctuation? Add a filter in the loop.
Need to sort by frequency? Use LinkedHashMap or sort entries manually.
Looking to highlight the first repeating character? You can break out of the loop as soon as a repeat is found.
This simple use of HashMap elegantly solves a common string processing task. Want help extending it to Unicode characters, user input, or performance tuning? Just tap me on the shoulder—I’ve got ideas ๐ค
This Content Sponsored by Buymote Shopping app
BuyMote E-Shopping Application is One of the Online Shopping App
Now Available on Play Store & App Store (Buymote E-Shopping)
Click Below Link and Install Application: https://buymote.shop/links/0f5993744a9213079a6b53e8
Sponsor Content: #buymote #buymoteeshopping #buymoteonline #buymoteshopping #buymoteapplication
No comments:
Post a Comment