In this program, we will check for duplicate characters in a String and count the number of times each character is repeated using Java.
package com.topjavatutorial; import java.util.HashMap; import java.util.Map; public class Demo { public static void main(String[] args) { String str = "topjavatutorial"; int count = 0; char c; Map<Character, Integer> map = new HashMap<Character, Integer>(); for (int i = 0; i < str.length(); i++) { c = str.charAt(i); if (map.containsKey(c)) { count = map.get(c); map.put(c, ++count); } else { map.put(c, 1); } } System.out.println(map); } }
Output :
{p=1, a=3, r=1, t=3, u=1, v=1, i=1, j=1, l=1, o=2}
© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post