Learn how to count occurrences of int in array in java with example. inteview question to find character from String in Java.
1. Overview of count Occurrences of int in array in Java
Well, so good so far, it’s time to check the basics of java and the basic algorithm to find a number of occurrences of all numbers from the int array. There are different ways to get this done but this is simple and straightforward. This is one of the interview questions which generally can ask in any level of Java interview, specially 1 to 5 years of experience in java.
2. Example of Occurences of int array in Java
package com.mysoftkey.util; import java.util.HashMap; import java.util.Map; /** * * This java class is used to find which element * in an array occurred how many times. * * @author ranjeet jha * */ public class IntOccurrenceCountInArrayExample { public static void main(String[] args) { // an nput Array int[] intArray = new int[] { 5, 1, 6, 4, 1, 4, 5, 2, 3, 7, 1, 3, 5, 6, 8, 2 }; // countMap holds key as int and value as count of an element Map<integer, integer=""> countMap = new HashMap(); for (int i = 0; i < intArray.length; i++) { int key = intArray[i]; if (countMap.containsKey(key)) { int count = countMap.get(key); count++; countMap.put(key, count); } else { countMap.put(key, 1); } } // print element and its occurrence which earlier System.out.println(" Number | time(s) |"); System.out.println(" (key ) |(occurrence)|"); System.out.println("-------------------------"); for (Map.Entry<integer, integer=""> val : countMap.entrySet()) { System.out.println(" | " + val.getKey() + " | " + val.getValue() + " |"); } System.out.println("-------------------------"); } }
There is obviously another way you can get this.
3. Program Output of occurrence of element
After running of above code for how to count element from an array in java gives the following output.
Number | time(s) | (key ) |(occurrence)| ------------------------- | 1 | 3 | | 2 | 2 | | 3 | 2 | | 4 | 2 | | 5 | 3 | | 6 | 2 | | 7 | 1 | | 8 | 1 | -------------------------
4. Reference
I hope you enjoyed this post How to count occurrences of int in array in java, you can visit Core Java tutorial for more blog post.
Please write your suggestions to improve this post. Happy Learning! 🙂