Find duplicate characters in a String and count the number of occurances using Java

You could use the following, provided String s is the string you want to process.

Map<Character,Integer> map = new HashMap<Character,Integer>();
for (int i = 0; i < s.length(); i++) {
  char c = s.charAt(i);
  if (map.containsKey(c)) {
    int cnt = map.get(c);
    map.put(c, ++cnt);
  } else {
    map.put(c, 1);
  }
}

Note, it will count all of the chars, not only letters.


Java 8 way:

"The quick brown fox jumped over the lazy dog."
        .chars()
        .mapToObj(i -> (char) i)
        .collect(Collectors.groupingBy(Object::toString, Collectors.counting()));

 void Findrepeter(){
    String s="mmababctamantlslmag";
    int distinct = 0 ;

    for (int i = 0; i < s.length(); i++) {

        for (int j = 0; j < s.length(); j++) {

            if(s.charAt(i)==s.charAt(j))
            {
                distinct++;

            }
        }   
        System.out.println(s.charAt(i)+"--"+distinct);
        String d=String.valueOf(s.charAt(i)).trim();
        s=s.replaceAll(d,"");
        distinct = 0;

    }

}

Tags:

Java