Filtering and Mapping Collections in Dart
In Dart, you can easily manipulate collections such as List
and Set
using the where
method for filtering and the map
method for transforming elements. These methods provide a functional programming style that enhances code readability and maintainability.
1. Filtering Collections with where
The where
method is used to filter elements in a collection based on a specified condition. It returns a new iterable containing only the elements that satisfy the condition defined in the provided function.
Example of Filtering a List
void main() {
List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filtering even numbers
Iterable<int> evenNumbers = numbers.where((number) => number.isEven);
// Printing the filtered list
print('Even numbers: $evenNumbers'); // Output: Even numbers: (2, 4, 6, 8, 10)
}
</int></int>
In this example, we create a list of integers and use the where
method to filter out even numbers. The condition is defined in the lambda function, which checks if each number is even. The result is an iterable containing only the even numbers.
2. Mapping Collections with map
The map
method is used to transform each element in a collection by applying a specified function. It returns a new iterable containing the results of applying the function to each element in the original collection.
Example of Mapping a List
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
// Mapping to square each number
Iterable<int> squaredNumbers = numbers.map((number) => number * number);
// Printing the mapped list
print('Squared numbers: $squaredNumbers'); // Output: Squared numbers: (1, 4, 9, 16, 25)
}
</int></int>
In this example, we create a list of integers and use the map
method to square each number. The transformation is defined in the lambda function, which multiplies each number by itself. The result is an iterable containing the squared values.
3. Chaining where and map
You can also chain the where
and map
methods to perform filtering and mapping in a single expression. This allows for concise and expressive code.
Example of Chaining where and map
void main() {
List<int> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filtering even numbers and then mapping to square them
Iterable<int> squaredEvenNumbers = numbers
.where((number) => number.isEven)
.map((number) => number * number);
// Printing the result
print('Squared even numbers: $squaredEvenNumbers'); // Output: Squared even numbers: (4, 16, 36, 64, 100)
}
</int></int>
In this example, we first filter the even numbers from the list and then square each of those numbers in a single expression. The result is an iterable containing the squared values of the even numbers.
4. Conclusion
Filtering and mapping collections in Dart using the where
and map
methods provide a powerful and expressive way to manipulate data. These methods enhance code readability and allow for functional programming patterns, making it easier to work with collections in Dart applications.