To filter items of a set based on a condition in Dart, you can use the where method to apply a filtering predicate and create a new set from the filtered items.
In this example,
numberSet
using the Set
type, which contains integer values 1
, 5
, 10
, 15
, and 20
.where
method on numberSet
to filter the numbers greater than 5 using a lambda function as the filtering condition.filteredSet
using the Set
constructor with the filtered items from the where
method.filteredSet
and print each filtered item to the console.void main() {
var numberSet = {1, 5, 10, 15, 20};
var filteredSet = numberSet.where((num) => num > 5).toSet();
filteredSet.forEach((num) => print(num));
}
10 15 20
In this example,
stringSet
using the Set
type, which contains string values 'apple'
, 'banana'
, 'cherry'
, 'date'
, and 'grape'
.where
method on stringSet
to filter the strings containing the letter 'a' using a lambda function as the filtering condition.filteredStringSet
using the Set
constructor with the filtered items from the where
method.filteredStringSet
and print each filtered string to the console.void main() {
var stringSet = {'apple', 'banana', 'cherry', 'date', 'grape'};
var filteredStringSet = stringSet.where((str) => str.contains('a')).toSet();
filteredStringSet.forEach((str) => print(str));
}
apple banana grape
In this tutorial, we learned How to Filter Items of a Set based on a Condition in Dart language with well detailed examples.