Sunday, August 22, 2021

Find frequency of character of a string using hashmap.

 public class MainApp {

public static void main(String[] args) {

String input = "aabbbcccdeefghijkkkkkk";

calculateFrequency(input);

}

private static void calculateFrequency(String input) {

Map<Character, Integer> frequency = new HashMap();

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

if (frequency.containsKey(input.charAt(i))) {

frequency.put(input.charAt(i), frequency.get(input.charAt(i)) + 1);

} else {

frequency.put(input.charAt(i), 1);

}

}

Set<Character> keySet = frequency.keySet();

for (Character c : keySet) {

System.out.println(c + ":" + frequency.get(c));

}

}

}


No comments:

Post a Comment

Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...