count duplicate character in string - Java & Python

 Python:

a = "ramanrayat"
d = {}
for i in range(len(a)):
if(a[i] not in d):
d[a[i]]=1
else:
d[a[i]]=d[a[i]]+1

for j in d:
if d[j]>1:
print(j+","+str(d[j]))

Java:


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class test123 {


public static void main(String[] args) {
String text = "raman rayat";
HashMap<Character, Integer> hm = new HashMap<>();
for(int i = 0;i<text.length();i++){
if(!hm.containsKey(text.charAt(i)))
{
if((text.charAt(i)!=' ')){
hm.put(text.charAt(i),1);
}
}else{
hm.put(text.charAt(i),hm.get(text.charAt(i))+1);
}
}

for(Map.Entry<Character,Integer> item: hm.entrySet()){
char key =item.getKey();
int value = item.getValue();

if(value>1){
System.out.println(key+","+value);
}

}

Comments

Popular posts from this blog

Rest Assured

Sort (Bubble) - Java

Rotate the String from position - Java