/** * @author lautturi.com * Java example: print frequencies of all elements using TreeMap */ import java.util.*; public class Lautturi { // This function prints frequencies of all elements static void printFreq(int arr[]) { // Creates an empty TreeMap TreeMap<Integer, Integer> tmap = new TreeMap<Integer, Integer>(); // Traverse through the given array for (int i = 0; i < arr.length; i++) { Integer c = tmap.get(arr[i]); // If this is first occurrence of element if (tmap.get(arr[i]) == null) tmap.put(arr[i], 1); // If elements already exists in hash map else tmap.put(arr[i], ++c); } // Print result for (Map.Entry m:tmap.entrySet()) System.out.println("Frequency of " + m.getKey() + " is " + m.getValue()); } public static void main(String[] args) { int[] arr = { 11,4,12,7,55,8,12,8,13,55,12,7 }; printFreq(arr); } }
output:
Frequency of 4 is 1 Frequency of 7 is 2 Frequency of 8 is 2 Frequency of 11 is 1 Frequency of 12 is 3 Frequency of 13 is 1 Frequency of 55 is 2