I can map list in Dart:
[1,2,3].map((e) => e + 1)
but how can I flatMap this list? Code presented below does not work.
[1,2,3].flatMap((e) => [e, e+1])
List, Set, Queue are iterable while Maps are not. Iterable collections can be changed i.e. their items can be modified, add, remove, can be accessed sequentially. The map doesn't extend iterable.
expand
method is equivalent to flatMap in Dart.
[1,2,3].expand((e) => [e, e+1])
What is more interesting, the returned Iterable
is lazy, and calls fuction for each element every time it's iterated.
Coming from Swift, flatMap
seems to have a little different meaning than the OP needed. This is a supplemental answer.
Given the following two dimensional list:
final list = [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]];
You can convert it into a single dimensional iterable like so:
final flattened = list.expand((element) => element);
// (1, 2, 2, 3, 3, 3, 4, 4, 4, 4)
Or to a list by appending toList
:
final flattened = list.expand((element) => element).toList();
// [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With