I'm given a code that asks us to have the user input a set of integers(they can be positive or negative). Then the code goes through the list and counts the occurence of each number. Once it reaches the end, the code displays ONLY the number with the most occurrences, or numbers if they both have the same # of occurences an it is the largest # of occurences. (Ex. The user inputs [4, 3, 7, 4, 5, 3], and the program displays 'The input numbers with the most occurences are [4, 3], and they occur 2 times.). I have written most of the code, but now I am stuck on how to get it to display only the numbers with the highest occurence! Please help point me in the right direction!

import java.util.*;
public class CountOccurence {
    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a list of integers(values can be either positive or negative). Enter 0 to terminate input.");
    int numInput = input.nextInt();
    Integer[] listOfNumbers = formNumberList(numInput); 
    Map<Integer, Integer> numberList = new HashMap<Integer, Integer>();
    while(true) {
        if (numInput != 0) {
            for (int i = 0; i < listOfNumbers.length; i++) {
                Integer numberKey = listOfNumbers[i];

                if(numberKey > 0) {
                    if (!numberList.containsKey(numberKey)) {
                        numberList.put(numberKey, 1);
                    else {
                        int numberCount = numberList.get(numberKey);
                        numberList.put(numberKey, numberCount);

            if (numInput == 0)


    public static Integer[] formNumberList(int numInput) {
        Integer[] number = new Integer[numInput];
        return number;

You can loop through the numberList examining each number and its count. Take the first number as being the highest and store it in another variable e.g. int highestCount.
For each number in the list, compare it's count to highestCount. If it is higher, replace highestCount with the new count and store the number as well.
If a number has the same count as highestCount you'll want to keep it as well, dumping it only when highestCount is again replaced but another higher value.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.