Calculate The Second Highest Frequency


/ Published in: Java
Save to your folder(s)

Calculate The Second Highest Frequency
Write a method that accepts a String and returns the character with the second highest frequency. For example "aabbbc" would return 'a'. If the string contains spaces, they can be disregarded from the count.


Copy this code and paste it in your HTML
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.Comparator;
  4. import java.util.HashMap;
  5. import java.util.List;
  6. import java.util.Map;
  7.  
  8. public class FrequencyFinder {
  9.  
  10. public static void main(String[] args) {
  11. String str = "aaabbbaaacccc aaaaddddd";
  12. findSecondHighestFreq(str);
  13. }
  14.  
  15. private static char findSecondHighestFreq(String inStr) {
  16. char secondChar = 0;
  17. Map<Character, Integer> charMap = new HashMap<Character, Integer>();
  18. scanChar(inStr.toCharArray(), charMap);
  19.  
  20. List<Map.Entry<Character,Integer>> entryList = new ArrayList<Map.Entry<Character,Integer>>(charMap.entrySet());
  21. Collections.sort(entryList,
  22. new Comparator<Map.Entry<Character,Integer>>() {
  23. public int compare(Map.Entry<Character,Integer> a, Map.Entry<Character,Integer> b) {
  24. return b.getValue().compareTo(a.getValue());
  25. }
  26. });
  27.  
  28. System.out.println("2nd most freq: key="+entryList.get(1).getKey()+", count="+entryList.get(1).getValue());
  29.  
  30. return secondChar;
  31. }
  32.  
  33. private static void scanChar(char[] inCharArr, Map<Character, Integer> charMap) {
  34. for (char chLocal : inCharArr) {
  35. if (chLocal==' ') {
  36. // ignore space character
  37. continue;
  38. }
  39. if (!charMap.containsKey(chLocal)){
  40. charMap.put(chLocal, 1);
  41. } else {
  42. charMap.put(chLocal, (charMap.get(chLocal)+1));
  43. }
  44. }
  45. }
  46.  
  47. }

URL: http://java.dzone.com/articles/thursday-code-puzzler-second

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.