Posted By

rnavanee on 07/19/13


Tagged

java collection puzzle


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Priestd09


Calculate The Second Highest Frequency


 / Published in: Java
 

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

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.

  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. }

Report this snippet  

You need to login to post a comment.