Monday, May 2, 2022

Question 5 : How to find duplicate characters in String in java?

 Solution:  Here is a solution to find duplicate characters in String.

  1. Create a HashMap and the character of String will be inserted as key and its count as value.
  2. If HashMap already contains char, increase its count by 1, else put char in HashMap.
  3. If the value of Char is more than 1, that means it is a duplicate character in that String.

Java Program to find duplicate Characters in a String:

import java.util.HashMap; import java.util.Map; import java.util.Set; public class DuplicateCharFinder { public void findIt(String str) { Map<Character, Integer> baseMap = new HashMap<Character, Integer>(); char[] charArray = str.toCharArray(); for (Character ch : charArray) { if (baseMap.containsKey(ch)) { baseMap.put(ch, baseMap.get(ch) + 1); } else { baseMap.put(ch, 1); } } Set<Character> keys = baseMap.keySet(); for (Character ch : keys) { if (baseMap.get(ch) > 1) { System.out.println(ch + " is " + baseMap.get(ch) + " times"); } } } public static void main(String a[]) { DuplicateCharFinder dcf = new DuplicateCharFinder(); dcf.findIt("India is my country"); } }


When you run the above program, you will get the below output:
is 3 times i is 2 times n is 2 times y is 2 times

Don't miss the next article!

Be the first to be notified when a new article or Kubernetes experiment is published.


You may also like

a
Kubernetes AWS Java Coding Question
Microservices Core Java Python
Spring Framework AI/MLSpring Boot