Filtering Collections in Dart Using where
The where
method in Dart is a powerful way to filter elements from collections such as lists and sets based on a specified condition. This method returns an iterable containing elements that satisfy the given predicate.
Filtering Lists
Example of Filtering with where
You can use the where
method to filter a list based on specific criteria. Here’s an example:
void main() {
List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter even numbers
Iterable<int> evenNumbers = numbers.where((number) => number.isEven);
print(evenNumbers.toList()); // Output: [2, 4, 6, 8, 10] }
Filtering with Multiple Conditions
You can also combine conditions in the where
method:
void main() {
List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter numbers greater than 5 and even Iterable<int> filteredNumbers = numbers.where((number) => number > 5 && number.isEven);
print(filteredNumbers.toList()); // Output: [6, 8, 10] }
Filtering Sets
Example of Filtering with where
Similar to lists, you can filter sets using the where
method:
void main() {
Set<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Filter odd numbers Iterable<int> oddNumbers = numbers.where((number) => number.isOdd);
print(oddNumbers.toSet()); // Output: {1, 3, 5, 7, 9} }
Filtering Maps
Filtering Keys or Values in Maps
You can filter the keys or values of a map using the where
method on the map's keys or values.
Example of Filtering Map Values
void main() {
Map<String, int> ages = {
'Alice': 30,
'Bob': 25,
'Charlie': 35,
'David': 28,
};
// Filter names with age greater than 28
Iterable<String> filteredNames = ages.keys.where((name) => ages[name]! > 28);
print(filteredNames.toList()); // Output: [Alice, Charlie, David] }
Example of Filtering Map Entries
You can also filter map entries based on both the key and value:
void main() {
Map<String, int> ages = {
'Alice': 30,
'Bob': 25,
'Charlie': 35,
'David': 28,
};
// Filter entries where age is greater than 28
Iterable<MapEntry<String, int>> filteredEntries = ages.entries.where((entry) => entry.value > 28);
// Convert filtered entries back to a map
Map<String, int> filteredMap = Map.fromEntries(filteredEntries);
print(filteredMap); // Output: {Alice: 30, Charlie: 35, David: 28}
}
Conclusion
The where
method in Dart is a versatile tool for filtering collections such as lists, sets, and maps. By providing a predicate function, you can easily extract elements that meet specific conditions, facilitating effective data manipulation and analysis. Mastering the use of where
will enhance your coding efficiency when working with collections in Dart.
PLAY QUIZ