Home > database >  Dart equivalent to get an element of a sequence and transform it fluently through a pipeline
Dart equivalent to get an element of a sequence and transform it fluently through a pipeline

Time:12-23

What is Dart equivalent to get an element of a sequence and transform it with a map() fluently through a pipeline.

Something like doing in Java streams:

var result = ....findFirst().map(elem -> transform(elem)).get();

CodePudding user response:

It does not really make much sense to have a "pipeline" for a single event (if that was what you mean by the findFirst() call). But if you want to, you can combine something with where() and take() so you keep the Iterable and therefore be able to use map on it:

void main() {
  print(
    [1, 2, 3]
        .where((element) => element == 2)
        .take(1) // Could also be skipped because of .first later
        .map((e) => e.toRadixString(2))
        .map((e) => e.padLeft(8, '0'))
        .map((e) => 'Number in binary is: $e')
        .first,
  ); // Number in binary is: 00000010
}
  •  Tags:  
  • dart
  • Related