[Java] how to find most repeated element from an array?
I want to find most repeated element from an array, how can I do that in Java?
1 Answer
4 years ago by Eleven
To do this in Java, we can create a Map with key as element and value as total occurrences, then we can iterate over the map to see the max value to find the most repeated word. Following code shows how to do that
import java.util.*;
public class JavaArrays {
public static void main(String[] args) {
String[] colors = { "red", "green", "blue", "orange", "maroon", "blue" };
Map<String, Integer> colorVsCount = new HashMap<>();
for (String color : colors) {
if(colorVsCount.containsKey(color)) {
colorVsCount.put(color, colorVsCount.get(color) + 1);
} else {
colorVsCount.put(color, 1);
}
}
int maxCount = 0;
String mostRepeatedElement = null;
for(Map.Entry<String, Integer> entry : colorVsCount.entrySet()) {
if(entry.getValue() > maxCount) {
maxCount = entry.getValue();
mostRepeatedElement = entry.getKey();
}
}
System.out.println("Most repeated element is: " + mostRepeatedElement);
}
}
Output:
Most repeated element is: blue
Try the code online here: https://onecompiler.com/java/3xmsyasft
4 years ago by Karthik Divi