Array In Dart
[1]. Arrays are Lists
List basics
Dart supports List literals like JavaScript. A simple Dart list:
main() {
var list = [1,2,3];
print( list is List ); // true
}
Get the list's length, or number of elements inside of the list:
main() {
var list = [1,2,3];
print( list.length ); // 3
}
Access the second element in the list: (notice how Dart list indexes are 0 based, i.e. 0 is the first element, 1 is the second element, etc)
main() {
var list = [1,2,3];
print( list[1] ); // 2
}
If you try to reference an element that is outside the length of the list, you'll get an IndexOutOfRangeException.
main() {
var list = [1,2,3];
print( list[5] );
// Unhandled exception: IndexOutOfRangeException
}
Add an element to a list constructed from a list literal:
main() {
List list = [1,2,3];
list.add(4);
print( list.length ); // 4
}
Now is a good time to point out that the add(object) method is optional. That is, not all implementations of List have to support it. I don't personally like optional methods
An example of a List that you can't add to is the fixed size List, as constructed by:
main() {
var list = new List(3);
list.add(4);
// this throws an UnsupportedOperationException:
//Cannot add to a non-extendable array
// exception thrown for Lists constructed with an initial size
}
It's important to know that when you construct a fixed size List, that the List itself is allocated to that size and filled with nulls for the size of the List. For example:
main() {
var list = new List(5); // [null,null,null,null,null]
print(list[0]); // null
}
Lists in Dart are not associative arrays. That is, the following code will NOT work in Dart:
main() {
var list = new List(); // no initial size! aka EMPTY
list[3] = 'hello'; // IndexOutOfRangeException
}
Remove an element from a list:
main() {
List list = [1,2,3];
list.removeRange(1, 1); // remove only the second element
print( list.length ); // 2
}
To print the elements of a List, we need to add a map() function to eventually convert a List to a List<String> because Strings.join only takes a List<String>. The Dart libs are lacking a map function on collections (see bug 945).
List map(List list, converter(x)) {
final List result = [];
for (final x in list) {
result.add(converter(x));
}
return result;
}
List<String> listToStrings(List list) {
return map(list, (x) => x.toString());
}
main() {
List list = [1,2,3];
print( Strings.join( listToStrings(list), ',' )); // 1,2,3
}
Sorting
Sorting a List takes advantage of Dart's function support.
main() {
var list = [4,1,2];
list.sort(compare(a,b) {
if (a == b) {
return 0;
} else if (a > b) {
return 1;
} else {
return -1;
}
});
// list is now 1,2,4
}
Iterating
Iterating over a List can be done in at least four ways. The standard, most familiar way is the for loop:
main() {
var list = [4,1,2];
for (var x = 0; x < list.length; x++) {
print(x);
}
}
There's a more terse way of using for if you don't need the current iteration index:
main() {
var list = [4,1,2];
for (final x in list) {
print(x);
}
}
The verbose way to say the above is to use a formal Iterator from the List:
main() {
var list = [4,1,2];
Iterator i = list.iterator();
while (i.hasNext()) {
print(i.next());
}
}
And finally, if you just want to apply a function to each element of the List, use forEach:
main() {
var list = [4,1,2];
list.forEach(f(e) => print(e));
}
Filtering
The Collection interface, which List extends, provides a filter method, which returns a new collection with only the elements that satisfy a condition.
An example of filtering:
main() {
var list = [4,1,2];
var evens = list.filter(f(e) => e % 2 == 0);
printList(evens); // 4,2
}
Of course, you don't need to inline the filtering function. Passing in a function also works:
isEven(x) => x % 2 == 0;
main() {
var list = [4,1,2];
var evens = list.filter(isEven);
printList(evens);
}
#1. forEach()
Runs a function on each element in the listvar fruits = [‘banana’, ‘pineapple’, ‘watermelon’];
fruits.forEach((fruit) => print(fruit));
// => banana pineapple watermelon
#2. map()
Produces a new list after transforming each element in a given listvar mappedFruits = fruits.map((fruit) => ‘I love $fruit’).toList();
print(mappedFruits);
// => ['I love banana', ‘I love pineapple’, ‘I love watermelon’]
#3. contains()
Checks to confirm that the given element is in the listvar numbers = [1, 3, 2, 5, 4];
print(numbers.contains(2)); // => true
#4. sort()
Order the elements based on the provided ordering functionnumbers.sort((num1, num2) => num1 - num2); // => [1, 2, 3, 4, 5]
#5. reduce(), fold()
Compresses the elements to a single value, using the given functionvar sum = numbers.reduce((curr, next) => curr + next);
print(sum); // => 15
const initialValue = 10;
var sum2 = numbers.fold(initialValue, (curr, next) => curr + next);
print(sum2); // => 25
#6. every()
Confirms that every element satisfies the testList<Map<String, dynamic>> users = [
{ “name”: ‘John’, “age”: 18 },
{ “name”: ‘Jane’, “age”: 21 },
{ “name”: ‘Mary’, “age”: 23 },
];
var is18AndOver = users.every((user) => user[“age”] >= 18);
print(is18AndOver); // => true
var hasNamesWithJ = users.every((user) => user[“name”].startsWith('J'));
print(hasNamesWithJ); // => false
#7. where(), firstWhere(), singleWhere()
Returns a collection of elements that satisfy a test.
// See #6 for users list
var over21s = users.where((user) => user[“age”] > 21);
print(over21s.length); // => 1
var nameJ = users.firstWhere((user) => user[“name”].startsWith(‘J’), orElse: () => null);
print(nameJ); // => {name: John, age: 18}
var under18s = users.singleWhere((user) => user[“age”] < 18, orElse: () => null);
print(under18s); // => null
firstWhere() returns the first match in the list, while singleWhere() returns the first match provided there is exactly one match.#8. take(), skip()
Returns a collection while including or skipping elementsvar fiboNumbers = [1, 2, 3, 5, 8, 13, 21];
print(fiboNumbers.take(3).toList()); // => [1, 2, 3]
print(fiboNumbers.skip(5).toList()); // => [13, 21]
print(fiboNumbers.take(3).skip(2).take(1).toList()); // => [3]
#9. List.from()
Creates a new list from the given collectionvar clonedFiboNumbers = List.from(fiboNumbers);
print(‘Cloned list: $clonedFiboNumbers’);
As of Dart 2.0, the new keyword is optional when instantiating objects.#10. expand()
Expands each element into zero or more elementsvar pairs = [[1, 2], [3, 4]];
var flattened = pairs.expand((pair) => pair).toList();
print(‘Flattened result: $flattened’); // => [1, 2, 3, 4]
var input = [1, 2, 3];
var duplicated = input.expand((i) => [i, i]).toList();
print(duplicated); // => [1, 1, 2, 2, 3, 3]
Comments
Post a Comment