## Posted By

rnavanee on 07/19/13

## Who likes this?

1 person have marked this snippet as a favorite

# Calculate The Second Highest Frequency

/ Published in: Java

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.

`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));			}		}	} }`