Report this

What is the reason for this report?

Java program for

Posted on April 18, 2025

most repeated numbers in Java



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hey!

You’ll probably want to use something like a HashMap to count occurrences.

Here’s a great place to start: DigitalOcean’s Java tutorials. Super beginner-friendly and well-written!

https://www.digitalocean.com/community/tags/java

- Bobby

Heya,

Here’s a simple Java program that finds the most repeated number(s) in an array of integers:

import java.util.*;

public class MostRepeatedNumbers {
    public static void main(String[] args) {
        int[] numbers = {4, 5, 6, 7, 4, 6, 4, 6, 6, 2, 4};

        Map<Integer, Integer> frequencyMap = new HashMap<>();
        int maxFrequency = 0;

        // Count frequency of each number
        for (int num : numbers) {
            int count = frequencyMap.getOrDefault(num, 0) + 1;
            frequencyMap.put(num, count);
            maxFrequency = Math.max(maxFrequency, count);
        }

        // Find number(s) with max frequency
        List<Integer> mostFrequent = new ArrayList<>();
        for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
            if (entry.getValue() == maxFrequency) {
                mostFrequent.add(entry.getKey());
            }
        }

        // Print results
        System.out.println("Most repeated number(s): " + mostFrequent);
        System.out.println("Frequency: " + maxFrequency);
    }
}

Sample Output:

Most repeated number(s): [6]
Frequency: 4
  • It uses a HashMap to count how many times each number appears.

  • Then it determines the maximum frequency and filters for numbers that appear that many times.

Let me know if you’d like a version that works with user input or with lists instead of arrays!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.