To find the element with the minimum number of occurrences in a list in Java, you can use a HashMap to count the occurrences.
In this example,
java.util
package.data
with several integer elements.HashMap
to count the occurrences of each element.import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> data = Arrays.asList(1, 2, 2, 3, 3, 3, 4);
Map<Integer, Integer> count = new HashMap<>();
for (int num : data) {
count.put(num, count.getOrDefault(num, 0) + 1);
}
int leastCommon = data.get(0);
int minCount = Collections.min(count.values());
for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
if (entry.getValue() == minCount) {
leastCommon = entry.getKey();
break;
}
}
System.out.println("Element with the minimum occurrences is: " + leastCommon);
}
}
Element with the minimum occurrences is: 1
In this example,
java.util
package.words
with several string elements.HashMap
to count the occurrences of each element.import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "apple", "orange", "banana", "apple");
Map<String, Integer> count = new HashMap<>();
for (String word : words) {
count.put(word, count.getOrDefault(word, 0) + 1);
}
String leastCommon = words.get(0);
int minCount = Collections.min(count.values());
for (Map.Entry<String, Integer> entry : count.entrySet()) {
if (entry.getValue() == minCount) {
leastCommon = entry.getKey();
break;
}
}
System.out.println("Element with the minimum occurrences is: " + leastCommon);
}
}
Element with the minimum occurrences is: orange
In this tutorial, we learned How to find the Element with Minimum Number of Occurrences in a List in Java language with well detailed examples.