How to count occurrence of int in array in java

Connect with

Oracle Java
Well, so good so far, it’s time to check the basic of java and basic of algorithm to find number of occurrence of all numbers from int array. There are different way to get this done but this is simple and straight forward. This is one of the interview question which generally can asked in any level of Java interview, specially 1 to 5 years of experience 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 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 val : countMap.entrySet()) {
	  System.out.println(" |    " + val.getKey() + "  | " + val.getValue() + "         |");
	}
	System.out.println("-------------------------");
  }

}

There are obviously another way you can get this .

Program Output of occurrence of element

After running of above code for how to count element from array in java gives following output.

 Number  |  time(s)  |
 (key )  |(occurrence)|
-------------------------
 |    1  | 3         |
 |    2  | 2         |
 |    3  | 2         |
 |    4  | 2         |
 |    5  | 3         |
 |    6  | 2         |
 |    7  | 1         |
 |    8  | 1         |
-------------------------

Write you comments or suggestion to improve this post.


Connect with

Leave a Reply

Your email address will not be published. Required fields are marked *