stream method

Iterable<T> stream()

If a value is present, returns an Iterable containing only that value, otherwise returns an empty Iterable.

API Note

This method can be used to transform an Iterable of optional elements to an Iterable of present value elements:

Iterable<Optional<T>> optionals = ...;
Iterable<T> values = optionals.expand((opt) => opt.stream());

Returns the optional value as an Iterable.

Example

Optional<String> name = Optional.of("Iris");
Optional<String> empty = Optional.empty();

// Convert to iterable
Iterable<String> nameStream = name.stream();
print(nameStream.toList()); // ["Iris"]

Iterable<String> emptyStream = empty.stream();
print(emptyStream.toList()); // []

// Useful for functional processing
List<Optional<String>> optionals = [
  Optional.of("apple"),
  Optional.empty(),
  Optional.of("banana")
];

List<String> fruits = optionals
    .expand((opt) => opt.stream())
    .toList();
print(fruits); // ["apple", "banana"]

// Chain with other stream operations
List<String> upperFruits = optionals
    .expand((opt) => opt.stream())
    .map((fruit) => fruit.toUpperCase())
    .where((fruit) => fruit.startsWith('A'))
    .toList();
print(upperFruits); // ["APPLE"]

Implementation

Iterable<T> stream() {
  if (isEmpty()) {
    return <T>[];
  } else {
    return [_value as T];
  }
}