To find the element with the minimum number of occurrences in a list in Dart, you can use a Map to count the occurrences.
In this example,
data
with several integer elements.void main() {
List<int> data = [1, 2, 2, 3, 3, 3, 4];
Map<int, int> count = {};
for (var num in data) {
if (count.containsKey(num)) {
count[num] = count[num]! + 1;
} else {
count[num] = 1;
}
}
int leastCommon = data[0];
int minCount = data.length;
count.forEach((key, value) {
if (value < minCount) {
minCount = value;
leastCommon = key;
}
});
print('Element with the minimum occurrences is: \$leastCommon');
}
Element with the minimum occurrences is: 1
In this example,
words
with several string elements.void main() {
List<String> words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
Map<String, int> count = {};
for (var word in words) {
if (count.containsKey(word)) {
count[word] = count[word]! + 1;
} else {
count[word] = 1;
}
}
String leastCommon = words[0];
int minCount = words.length;
count.forEach((key, value) {
if (value < minCount) {
minCount = value;
leastCommon = key;
}
});
print('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 Dart language with well detailed examples.