Dart – Common Collection Methods
Last Updated :
30 Aug, 2020
List, Set, and Map share common functionality found in many collections. Some of this common functionality is defined by the Iterable class, which List and Set implement.
1. isEmpty() or isNotEmpty:
Use isEmpty or isNotEmpty to check whether a list, set, or map has items:
Example:
Dart
void main(){
var coffees = [];
var teas = [ 'green' , 'black' , 'chamomile' , 'earl grey' ];
print(coffees.isEmpty);
print(teas.isNotEmpty);
}
|
Output:
true
true
2. forEach():
To apply a function to each item in a list, set, or map, you can use forEach():
Example:
Dart
void main(){
var teas = [ 'green' , 'black' , 'chamomile' , 'earl grey' ];
var loudTeas = teas.map((tea) => tea.toUpperCase());
loudTeas.forEach(print);
}
|
Output:
GREEN
BLACK
CHAMOMILE
EARL GREY
3.where():
Use Iterable’s where() method to get all the items that match a condition. Use Iterable’s any() and every() methods to check whether some or all items match a condition.
Example:
Dart
void main(){
var teas = [ 'green' , 'black' , 'chamomile' , 'earl grey' ];
bool isDecaffeinated(String teaName) =>
teaName == 'chamomile' ;
print(teas.any(isDecaffeinated));
print(!teas.every(isDecaffeinated));
}
|
Output:
true
true
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...