GenericStream<T>.generate constructor
- T supplier()
Creates a GenericStream by repeatedly calling a supplier function.
Example
final random = GenericStream.generate(() => Random().nextInt(100))
.limit(5);
A sequence of elements supporting sequential and parallel aggregate operations.
The following example illustrates an aggregate operation using GenericStream:
final sum = widgets.stream()
.filter((w) => w.color == RED)
.mapToInt((w) => w.weight)
.sum();
In this example, widgets
is a List of Widget
objects. We create a stream
of Widget
objects via List.stream
, filter it to produce a stream containing
only the red widgets, and then transform it into a stream of int
values
representing the weight of each red widget. Then this stream is summed to
produce a total weight.
In addition to GenericStream, which is a stream of object references, there are primitive specializations for IntStream and DoubleStream, all of which are referred to as "streams" and conform to the characteristics and restrictions described here.
To perform a computation, stream operations are composed into a stream pipeline. A stream pipeline consists of a source (which might be an array, a collection, a generator function, an I/O channel, etc), zero or more intermediate operations (which transform a stream into another stream, such as filter), and a terminal operation (which produces a result or side-effect, such as count or forEach). Streams are lazy; computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed.
Example Usage
final people = [
Person('Alice', 25, 'Engineering'),
Person('Bob', 30, 'Marketing'),
Person('Charlie', 35, 'Engineering'),
Person('Diana', 28, 'Sales'),
];
// Filter and collect
final engineers = GenericStream.of(people)
.filter((p) => p.department == 'Engineering')
.toList();
// Transform and reduce
final totalAge = GenericStream.of(people)
.mapToInt((p) => p.age)
.sum();
// Group by department
final byDepartment = GenericStream.of(people)
.collect(Collectors.groupingBy((p) => p.department));
// Complex pipeline
final result = GenericStream.of(people)
.filter((p) => p.age > 25)
.map((p) => p.name.toUpperCase())
.sorted()
.limit(2)
.collect(Collectors.joining(', '));
Implementation
factory GenericStream.generate(T Function() supplier) = GenericStreamImplementation<T>.generate;