Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatMap List in Dart?

Tags:

dart

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])
like image 217
bartektartanus Avatar asked Mar 22 '18 21:03

bartektartanus


People also ask

What is the difference between list and map in Dart?

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.


2 Answers

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.

like image 168
bartektartanus Avatar answered Oct 21 '22 16:10

bartektartanus


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]
like image 36
Suragch Avatar answered Oct 21 '22 15:10

Suragch