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!
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.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.