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!
- 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);
}
}
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!
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Scale up as you grow — whether you're running one virtual machine or ten thousand.

From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.
