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!