Previously we have discussed the Program for
Java program to print Diamond ?
This is a program to count element occurrence , Here i'am using Scanner to take input from console
Java program to print Diamond ?
and HashMap to store element and his occurrence in array. We are using HashMap because it store data in form of Keys and Value pair. HashMap<K,V>.
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class CountElementOccurence{
public static void main(String[] args) {
try {
Scanner sc=new Scanner(System.in);
System.out.print("ENTER INPUT ARRAY SIZE : ");
int inputArraySize = sc.nextInt();
System.out.println("ENTER "+inputArraySize+" ARRAY ELEMENTS :");
int[] inputArr=new int[inputArraySize];
for(int i=0;i<inputArraySize;i++){
inputArr[i] = sc.nextInt();
}
Map<Integer, Integer> map=new HashMap<Integer, Integer>();
for(int i=0;i<inputArr.length;i++){
if(map.containsKey(inputArr[i])){
map.put(inputArr[i], map.get(inputArr[i])+1);
}
else{
map.put(inputArr[i], 1);
}
}
int max = Collections.max(map.values());
List<Integer> keys = new ArrayList<Integer>();
for(Entry<Integer, Integer> entry : map.entrySet()){
if(entry.getValue() == max){
keys.add(entry.getKey());
}
}
System.out.println("OUTPUT\nElement\tCount");
System.out.println(Collections.min(keys)+"\t"+max);
}
catch (Exception e) {
System.err.println("** ENTER NUMERIC DIGITS ONLY **");
}
}
}
Program Output :-
ENTER INPUT ARRAY SIZE : 3
ENTER 3 ARRAY ELEMENTS :
1
1
5
OUTPUT
Element Count
1 2

No comments:
Post a Comment