Let's say I have an iterable (be it a map (keys), list, set, etc), and wish use Map() to transform it into another iterable with function f. However I wish for f to only return a value if a condition is met, after transforming it.
List<int> a = [1,2,3,4,5,6];
List<int> b = a.map((e) => (e % 2 == 0) ? e * 10 : null);
assert(b == [20,40,60]);
However this returns an error, as does any similar equivalent in map with mapEntry, such as:
Map<int, String> a = {1:a, 2:b, 3:c, 4:d, 5:e, 6:f};
Map<int, String> b = a.map((k,v) => (k % 2 == 0) ? MapEntry(k*10,v) : null);
assert(b.keys.toList<int>() == [20,40,60]);
Of course, there are ways to go around this by sacrificing efficiency and conciseness by looping over it before or after mapping the values to filter out unneeded values. Such as:
List<int> b = a.where((e) => e%2).map((e) => e * 10);
List<int> b = a.map((e) => e * 10).where((e) => e%2);
Or simply manually looping with for...in or forEach() and iterating over a while conditionally adding the changed result to b, but this would be lengthy codewise and would lack the optimizations map() would have for the specialized operation.
Do let me know if this is at all possible - micro-optimizations accumulate for big gains imho :).
Any help is much appreciated!
Of course, there are ways to go around this by sacrificing efficiency and conciseness by looping over it before or after mapping the values to filter out unneeded values.
Well, efficiency (as in performance) should not be affected since you are chaining iterators which handles values one by one. So using a where() should not be an issue here.
If you want a more compact solution you can do this (which creates a new List temporary for each element in a, which makes it less efficient):
List<int> b = a.expand((e) => [if (e % 2 == 0) e * 10]).toList();
For the Map case I think the best you can do is using a where. I thought about another solution but ended up with this mess:
Map<int, String> c = Map.fromEntries(a.entries.expand((e) => [if (e.key % 2 == 0) MapEntry(e.key * 10, e.value)]));
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