mapIndexedNotNull<R> method

Iterable<R> mapIndexedNotNull<R>(
  1. R transform(
    1. int index,
    2. T
    )
)

Returns a new lazy Iterable containing the results of applying the given transform function to each element of this collection, where the function takes two arguments: the index of the current element and the element itself, and filters out the elements for which the transform function returns null.

The transform function is invoked for each element in the collection with two arguments: the index of the current element and the element itself. If the result of the transform function is not null, it is included in the resulting iterable; otherwise, it is skipped.

  • Parameters:

    • transform: A function that takes an integer index and an element of type T and returns a result of type R or null.
  • Returns: A new lazy Iterable containing the non-null results of applying the transform function to each element of this collection.

  • Example:

    Iterable<String?> words = ['apple', 'banana', 'cherry'];
    Iterable<String> validWords = words.mapIndexedNotNull((index, word) {
      if (index % 2 == 0) {
        return word.toUpperCase();
      } else {
        return null;
      }
    });
    
    print(validWords); // Output: [APPLE, CHERRY]
    

Note: This method creates a new lazy Iterable and does not modify the original collection. It allows you to transform and filter elements based on their index within the collection.

Implementation

Iterable<R> mapIndexedNotNull<R>(R Function(int index, T) transform) sync* {
  var index = 0;
  for (var element in this) {
    final result = transform(index++, element);
    if (result != null) {
      yield result;
    }
  }
}