To find the element with the maximum number of occurrences in a list in Java, you can use a HashMap to count occurrences and iterate through the list.
In this example,
list
containing elements.countMap
to store element occurrences.countMap
for each element.countMap
.import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("a", "b", "c", "a", "b", "a");
Map<String, Integer> countMap = new HashMap<>();
for (String element : list) {
countMap.put(element, countMap.getOrDefault(element, 0) + 1);
}
String maxElement = Collections.max(countMap.entrySet(), Map.Entry.comparingByValue()).getKey();
System.out.println("Element with maximum occurrences: " + maxElement);
}
}
Element with maximum occurrences: a
In this example,
numbers
containing integers.countMap
to store integer occurrences.countMap
for each integer.countMap
.import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 2, 1, 1, 3, 1);
Map<Integer, Integer> countMap = new HashMap<>();
for (Integer num : numbers) {
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
}
Integer maxNumber = Collections.max(countMap.entrySet(), Map.Entry.comparingByValue()).getKey();
System.out.println("Number with maximum occurrences: " + maxNumber);
}
}
Number with maximum occurrences: 1
In this tutorial, we learned How to find the Element with Maximum Number of Occurrences in a List in Java language with well detailed examples.