Dart Lists and Collections

By pjain      Published May 1, 2020, 2:21 a.m. in blog Programming   

Part of Dart Series

Dart Collections, Data Structures, Functional Programming

Dart Collection classes overview

Arrays, Lists

lists can hold strings, boolean values, or any other valid Dart data type. In fact, you could even mix and match:

List stuff = ["Bob", "Jerry", "Tim", 15, 3.14, true];
    List<dynamic> stuff = ..  //equiv to 
List l = List(); 
List l2 = [];
list[i]
list.length
list.isEmpty  // also .isNotEmpty
list.clear()

void main() {
  List stuff = ["Bob", "Jerry", "Tim", 15, 3.14, true];
  for (int i = stuff.length-1; i>=0 ; i--) {
    print(stuff[i]);
  }
}
  • Using a typed list here ensures that the sum() function doesn't crash when it tries to add strings, numbers, and boolean values together. The parameter values can only be assigned a list of integers, so the code within the function can safely assume every element is an integer. List stuff = [15, 3.14, 7.0];

  • Add, remove, index in list

  • Note list is kept "packed" after removal, other items' indexes change
List<String> s = [];
s.add("PKJ"); s.add("MG"); s.add("Jan"); print(s); // [PKJ, MG, Jan]
s.remove("MG");print(s); // [PKJ, Jan] 
s.sort();
print(s.first,slast); //same as print(s[0],s[s.length -1]);
print(s.isEmpty);

Functions and Examples in Lists

contains

 var lovedGirls = ['Jill','Mary','Beth'];
 print(lovedGirls.contains('Mary')); // true

sort with custom ordering function

var ids = [1, 4, 5, 6, 6, 4, 4 ];
ids.sort((n1,n2)=&gt; num1-num2); // [1, 4, 4, 4, 5, 6, 6];

reduce(), fold()

Compresses the elements to a single value, using the given function

  • reduce var sum = ids.reduce((curr, next) => curr + next); print(sum); // => 15

  • fold const initialValue = 10; var sum2 = numbers.fold(initialValue, (curr, next) => curr + next); print(sum2); // => 25

Iterators in List

Simple for in and for loop

  • for in loop

    void printList(List list) { for (String element in list) { print(element); }

  • Using a simple for loop gives you an index

    for (var index = 0; index < lovedGirls.length; ++index) { final value = lovedGirls[index]; }

forEach

  • This iterates over each element e.g. you can print out or index over each one ..

    var lovedGirls = ['Jill','Mary','Beth'].map((girl) => 'I love $girl')).toList();

Iteration with Index over a list

map list elements

  • This produces a new list after transforming each element

    var lovedGirls = ['Jill','Mary','Beth'].map((girl) => 'I love $girl')).toList();

iterate from asMap() - list does NOT have a standard (index, obj) iterator, but you can

  • Note the .asMap creates an efficient immutable map - not allocating entities all over again. So it is about same in cost as for loop.

    myList.asMap().entries.map((entry) { int idx = entry.key; String val = entry.value; return something; }

Set - distinct keys

Removing Duplicates from a list

var ids = [1, 4, 4, 4, 5, 6, 6];
var distinctIds = ids.toSet().toList(); // [1, 4, 5, 6]
final distinctIds = [...{...ids}]; //same as above but using spread operators to be concise

// Set doesn't preserve the order. Here's another way using LinkedHashSet:
List&lt;String&gt; result = LinkedHashSet&lt;String&gt;.from(ids).toList(); // =&gt; ["a", "b", "c", "d"]

Map class

  • Map is the base map (defaults to LinkedHashMap) but it can have derivatives which affect eg iteration

Map initialization and acessors

  • construct - We don’t need to use new keyword anymore or declare the import import 'dart:collection'; // not needed as built into dart HashMap map = HashMap(); // is accepted.

Map<String, int> map1 = {'zero': 0, 'one': 1, 'two': 2};
var details = {'Username':'tom','Password':'pass@123'}; // SIMPLE var defaults map type 
Map map = Map(); // dynamic key, value
print(details); print(details.length);
var map2 = Map.from(details); 

Map 101

  • Keys are unique - at most one

  • Detailed Map Implementations - alters iterators Map map = Map(); if (map is LinkedHashMap) { // can find out type of object map print("This is a LinkedHashMap."); // yes it is! }

LinkedHashMap

It iterates in predictable key insertion order - this is default for new Map() constructors (Map(), Map.from(), Map.of()) will return a LinkedHashMap.

LinkedHashMap linkedHashMap = new LinkedHashMap&lt;int, String&gt;();
LinkedHashMap map2 = LinkedHashMap(); // dynamic key, value

HashMap

A plain unordered (no order is guaranteed),

HashMap hashMap = new HashMap&lt;int, String&gt;();
HashMap map1 = HashMap(); // dynamic key, value

SplayTreeMap

  • Sorted maps iterate the keys in sorted order. It is a self-balancing binary tree, frequently accessed elements will be moved more closely to the root of the tree.

    SplayTreeMap treeMap = new SplayTreeMap(); SplayTreeMap map3 = SplayTreeMap(); // dynamic key, value

Iteration in Map

Detailed Map Implementations - alters iterators HashMap is plain unordered (no order is guaranteed), LinkedHashMap iterates in key insertion order, Sorted maps iterate the keys in sorted order eg SplayTreeMap

It is generally not allowed to modify the map (add or remove keys) while an operation is being performed on the map, for example in functions called during a forEach or putIfAbsent call. Modifying the map while iterating the keys or values may also break the iteration.


0 comments

There are no comments yet

Add new comment

Similar posts

List++ Advanced Application Features

Interview Questions in Flutter

NAV: URL Launcher, Deep Links

NAV: Navigation Drawers