Counting occurrences in array java -
i want compute occurrences of each number in java array (like 1=?, 2=?, 3=?). how can array store more 10 value?
int [] arrynum = new int[]{4,4,4,3,4,5,4,3,4,4,4,5,4,5,5,5,4,3,2,15,4,3,4,6,4,3,4,5,4,2,4,5,4,3,2,5,4,3,5,4,0,4,3,4,5,4,3,0,4,5,4,3,5,4,2,3,2,3,4}; int[] counter = new int[] { 0, 0, 0, 0, 0,0 }; (int = 0; < arrynum.length; i++) { counter[arrynum[i] ]++; } (int = 0; < counter.length; i++){ system.out.println((i + 1) + ":" + counter[i]); }
public static void main(string[] args){ int[] arrynum = new int[] { 4, 4, 4, 3, 4, 5, 4, 3, 4, 4, 4, 5, 4, 5, 5, 5, 4, 3, 2, 15, 4, 3, 4, 6, 4, 3, 4, 5, 4, 2, 4, 5, 4, 3, 2, 5, 4, 3, 5, 4, 0, 4, 3, 4, 5, 4, 3, 0, 4, 5, 4, 3, 5, 4, 2, 3, 2, 3, 4 }; map<integer, integer> lookup = new hashmap<>(); (int key : arrynum) { if(lookup.containskey(key)) { lookup.put(key, lookup.get(key) + 1); } else { lookup.put(key, 1); } } (integer keys : lookup.keyset()) { system.out.println(keys + " found " + lookup.get(keys) + " times"); } }
Comments
Post a Comment