Revision: 64287
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at July 19, 2013 08:15 by rnavanee
Initial Code
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; public class FrequencyFinder { public static void main(String[] args) { String str = "aaabbbaaacccc aaaaddddd"; findSecondHighestFreq(str); } private static char findSecondHighestFreq(String inStr) { char secondChar = 0; Map<Character, Integer> charMap = new HashMap<Character, Integer>(); scanChar(inStr.toCharArray(), charMap); List<Map.Entry<Character,Integer>> entryList = new ArrayList<Map.Entry<Character,Integer>>(charMap.entrySet()); Collections.sort(entryList, new Comparator<Map.Entry<Character,Integer>>() { public int compare(Map.Entry<Character,Integer> a, Map.Entry<Character,Integer> b) { return b.getValue().compareTo(a.getValue()); } }); System.out.println("2nd most freq: key="+entryList.get(1).getKey()+", count="+entryList.get(1).getValue()); return secondChar; } private static void scanChar(char[] inCharArr, Map<Character, Integer> charMap) { for (char chLocal : inCharArr) { if (chLocal==' ') { // ignore space character continue; } if (!charMap.containsKey(chLocal)){ charMap.put(chLocal, 1); } else { charMap.put(chLocal, (charMap.get(chLocal)+1)); } } } }
Initial URL
http://java.dzone.com/articles/thursday-code-puzzler-second
Initial Description
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.
Initial Title
Calculate The Second Highest Frequency
Initial Tags
java
Initial Language
Java