In dart programming, Lists are used for the collection of data. We declare just variables instead of declaring a separate variable for each value of the collection. Lists are indexable so that we access the values using index ( starts from 0 ).
In this article, we will see how to compare two Lists in the dart. For example:
a = [ 1, 2, 3, 4, 5 ] b = [ 1, 2, 3, 4, 5 ] // a is equal to b c = [ 2, 3, 7, 3, 7, 9 ] d = [ 2, 5, 6, 9, 3, 4 ] // c is not equal to d
Methods:
For comparing two lists we have the following methods.
- Using the join( ) method
- Using forin loop
- Using dart Collection package
1. Using the join( ) method:
Join method is used for combining all the array elements and return as a String. Using the join method the steps are following.
- Get two Lists
- join them
- compare them
Implementation :
// Implementation of array comparison using join method
void main(){
var arr1 = [ 1, 2, 3, 4, 5, 6 ];
var arr2 = [ 1, 2, 3, 4, 5, 6 ];
// join both the array and compare them
var comp = arr1.join() == arr2.join();
// print The result
comp == true ? print("arr1 is equal to arr2") : print("arr1 is not equal to arr2");
}
Output:
arr1 is equal to arr2
2. Using forin loop :
Using for in loop the steps of comparison of two lists are following
- get two array
- create a function the returns a bool and pass both the array into it
- Using forin loop, iterate the first array
- now on each iteration check if the element of that index is matching with the second array or not
- if any item is not matching the return false.
Implementation:
// Implementation using forin loop
// creating a function that returns a boolean value
bool isEqual(var arr1, var arr2){
int i = 0;
for(var a in arr1){
// check if the value is equal to the second array at same index or not.
if(a != arr2[i]){
return false;
}
i++;
}
// If all the index are matching then return true
return true;
}
void main(){
var arr1 = [ 1, 4, 2, 5, 3, 6, 3, 7, 3 ];
var arr2 = [ 1, 4, 2, 5, 2, 6, 3, 7, 3 ];
var res = isEqual(arr1, arr2);
res ? print("arr1 is equal to arr2") : print("arr1 is not equal to arr2");
}
Output:
arr1 is not equal to arr2
3. Using dart collection package
Using the collection package you can check if two lists are equal or not. Steps for using collections following:
- Import collection package
- Get the Lists
- Use IterableEquality( ) function with equals( ) method
- inside equals( ) method pass the both lists
Implementation :
// implementation of List comparision using collection package
import 'package:collection/collection.dart';
void main() {
var arr1 = [ 1, 2, 3, 4, 5 ];
var arr2 = [ 1, 2, 3, 4, 5 ]
// check is the lists are equal
var isEqual = ListEquality().equals(arr1, arr2);
if(isEqual){
print("arr1 is equal to arr2");
}else{
print("arr1 is not equal to arr2");
}
}
Output:
arr1 is equal to arr2
