In Dart, the forEach
loop is used to iterate over each item in an iterable, such as a list, set, or map. It comes in handy when we want to loop through a collection or list.
The following is the syntax for the forEach()
method:
iterable.forEach((element) { ... });
The following program takes in a list of integers and returns a new list containing the repeated number.
void main() {// Declare list of integersList myList = [9,10,20,15,20,9,5,5];// Invoke getRepeatedNo() functiongetRepeatedNo(myList);}// Function that returns a list of repeated numbers in the listgetRepeatedNo(List numbers){List repeatedNumbers = [];List otherNumbers = [];numbers.forEach((x){if(otherNumbers.contains(x)){repeatedNumbers.add(x);}else{otherNumbers.add(x);}});print("Repeated number: $repeatedNumbers");print("List without repeated number: $otherNumbers");}
Line 3: We define a list of integers called myList()
.
Line 5: We invoke the getRepeatedNo()
function, which takes a list as its parameter.
Lines 9–25: We define a function called getRepeatedNo()
. This function takes a list of integers and returns the list of repeated numbers in the original list.
Line 10: We define a variable called repeatedNumbers
that will hold the repeated numbers.
Line 11: We define another variable called otherNumbers
that will hold distinct numbers.
Lines 12–20: We use the forEach()
method to iterate through the list passed into the getRepeatedNo()
function. Next, we use the if...else
statement to check if the value exists in the otherNumbers
list. If true, the value is added to the repeatedNumbers
list. Otherwise, the value is added to the otherNumbers
list.
Line 22: We display the repeated numbers using the print()
method.
Line 23: We display the distinct numbers using the print()
method.
Free Resources