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

The Solution to Find duplicate characters in a String and count the number of occurances using Java is


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.

~ Answered on 2012-10-29 10:40:24


Most Viewed Questions: