Documentation
¶
Overview ¶
Package stream provides a lazy, thread-safe, expressive stream processing framework inspired by Java 8 streams and backed by Go iterators (iter.Seq).
The package is designed to be cleanly dot-imported:
import . "github.com/BeamFoundry/rays/pkg/util/stream"
Example ¶
Example demonstrates filtering, mapping, and collecting a stream of integers.
// A pipeline filtering even numbers, doubling them, and collecting to a slice.
result := Stream[int]{}.From(1, 2, 3, 4, 5, 6).
Filter(func(n int) bool { return n%2 == 0 }).
Map(func(n int) int { return n * 2 }).
ToSlice()
fmt.Println(result)
Output: [4 8 12]
Index ¶
- type Collector
- type Collectors
- func (Collectors) AveragingFloat64[T any](mapper func(T) float64) Collector[T, *avgAcc, float64]
- func (Collectors) AveragingInt[T any](mapper func(T) int) Collector[T, *avgAcc, float64]
- func (Collectors) Counting[T any]() Collector[T, *int64, int64]
- func (Collectors) Filtering[T, A, R any](predicate func(T) bool, downstream Collector[T, A, R]) Collector[T, A, R]
- func (Collectors) FlatMapping[T, U, A, R any](mapper func(T) []U, downstream Collector[U, A, R]) Collector[T, A, R]
- func (Collectors) GroupingBy[T any, K comparable, A, D any](classifier func(T) K, downstream Collector[T, A, D]) Collector[T, map[K]A, map[K]D]
- func (this Collectors) GroupingBySlice[T any, K comparable](classifier func(T) K) Collector[T, map[K][]T, map[K][]T]
- func (Collectors) Joining(delimiter string, prefixAndSuffix ...string) Collector[string, *joinAcc, string]
- func (Collectors) Mapping[T, U, A, R any](mapper func(T) U, downstream Collector[U, A, R]) Collector[T, A, R]
- func (Collectors) MaxBy[T any](comparator func(a, b T) int) Collector[T, *Optional[T], Optional[T]]
- func (Collectors) MinBy[T any](comparator func(a, b T) int) Collector[T, *Optional[T], Optional[T]]
- func (Collectors) PartitioningBy[T, A, D any](predicate func(T) bool, downstream Collector[T, A, D]) Collector[T, map[bool]A, map[bool]D]
- func (this Collectors) PartitioningBySlice[T any](predicate func(T) bool) Collector[T, map[bool][]T, map[bool][]T]
- func (Collectors) Reducing[T any](identity T, op func(T, T) T) Collector[T, *T, T]
- func (Collectors) SummarizingFloat64[T any](mapper func(T) float64) Collector[T, *Float64SummaryStatistics, Float64SummaryStatistics]
- func (Collectors) SummarizingInt[T any](mapper func(T) int) Collector[T, *IntSummaryStatistics, IntSummaryStatistics]
- func (Collectors) SummingFloat64[T any](mapper func(T) float64) Collector[T, *float64, float64]
- func (Collectors) SummingInt[T any](mapper func(T) int) Collector[T, *int64, int64]
- func (Collectors) ToList[T any]() Collector[T, List[T], List[T]]
- func (Collectors) ToMap[T any, K comparable, V any](keyMapper func(T) K, valueMapper func(T) V, ...) Collector[T, map[K]V, map[K]V]
- func (Collectors) ToSet[T comparable]() Collector[T, Set[T], Set[T]]
- func (Collectors) ToSetSlice[T comparable]() Collector[T, map[T]struct{}, []T]
- func (Collectors) ToSlice[T any]() Collector[T, []T, []T]
- type Float64SummaryStatistics
- type IntSummaryStatistics
- type Stream
- func (this Stream[T]) AllMatch(predicate func(T) bool) bool
- func (this Stream[T]) AnyMatch(predicate func(T) bool) bool
- func (this Stream[T]) Close()
- func (this Stream[T]) Collect[R, A any](collector Collector[T, A, R]) R
- func (this Stream[T]) CollectWith[R any](supplier func() R, accumulator func(R, T) R, combiner ...func(R, R) R) R
- func (this Stream[T]) Count() int64
- func (this Stream[T]) Distinct() Stream[T]
- func (this Stream[T]) DistinctBy[K comparable](keySelector func(T) K) Stream[T]
- func (this Stream[T]) DropWhile(predicate func(T) bool) Stream[T]
- func (this Stream[T]) Filter(predicate func(T) bool) Stream[T]
- func (this Stream[T]) FindAny() Optional[T]
- func (this Stream[T]) FindFirst() Optional[T]
- func (this Stream[T]) FlatMap[R any](mapper func(T) Stream[R]) Stream[R]
- func (this Stream[T]) FlatMapSeq[R any](mapper func(T) iter.Seq[R]) Stream[R]
- func (this Stream[T]) FlatMapSlice[R any](mapper func(T) []R) Stream[R]
- func (this Stream[T]) ForEach(action func(T))
- func (this Stream[T]) ForEachOrdered(action func(T))
- func (this Stream[T]) From(elements ...T) Stream[T]
- func (this Stream[T]) FromChan(ch <-chan T) Stream[T]
- func (this Stream[T]) FromCollection(c Collection[T]) Stream[T]
- func (this Stream[T]) FromConcat(a, b Stream[T]) Stream[T]
- func (this Stream[T]) FromEmpty() Stream[T]
- func (this Stream[T]) FromGenerate(supplier func() T) Stream[T]
- func (this Stream[T]) FromIterate(seed T, f func(T) T) Stream[T]
- func (this Stream[T]) FromIterateWithPredicate(seed T, hasNext func(T) bool, f func(T) T) Stream[T]
- func (Stream[T]) FromRange[I IntegerConstraint](startInclusive, endExclusive I) Stream[I]
- func (Stream[T]) FromRangeClosed[I IntegerConstraint](startInclusive, endInclusive I) Stream[I]
- func (Stream[T]) FromSeq(seq iter.Seq[T]) Stream[T]
- func (this Stream[T]) FromSlice(slice []T) Stream[T]
- func (this Stream[T]) IsParallel() bool
- func (this Stream[T]) Limit(maxSize int64) Stream[T]
- func (this Stream[T]) Map[R any](mapper func(T) R) Stream[R]
- func (this Stream[T]) Max(comparator ...func(a, b T) int) Optional[T]
- func (this Stream[T]) MaxBy[K OrderedConstraint](keySelector func(T) K) Optional[T]
- func (this Stream[T]) Min(comparator ...func(a, b T) int) Optional[T]
- func (this Stream[T]) MinBy[K OrderedConstraint](keySelector func(T) K) Optional[T]
- func (this Stream[T]) NoneMatch(predicate func(T) bool) bool
- func (this Stream[T]) OnClose(handler func()) Stream[T]
- func (this Stream[T]) Parallel() Stream[T]
- func (this Stream[T]) Peek(action func(T)) Stream[T]
- func (this Stream[T]) Reduce(accumulator func(a, b T) T) Optional[T]
- func (this Stream[T]) ReduceWithIdentity(identity T, accumulator func(a, b T) T) T
- func (this Stream[T]) ReduceWithInitial[R any](identity R, accumulator func(R, T) R) R
- func (this Stream[T]) Seq() iter.Seq[T]
- func (this Stream[T]) Sequential() Stream[T]
- func (this Stream[T]) Skip(n int64) Stream[T]
- func (this Stream[T]) Sorted(comparator ...func(a, b T) int) Stream[T]
- func (this Stream[T]) SortedBy[K OrderedConstraint](keySelector func(T) K) Stream[T]
- func (this Stream[T]) SortedByDesc[K OrderedConstraint](keySelector func(T) K) Stream[T]
- func (this Stream[T]) SortedFunc(less func(a, b T) bool) Stream[T]
- func (this Stream[T]) TakeWhile(predicate func(T) bool) Stream[T]
- func (this Stream[T]) ToSlice() []T
- func (this Stream[T]) Unordered() Stream[T]
Examples ¶
- Package
- Collectors.Counting
- Collectors.GroupingBy
- Collectors.GroupingBySlice
- Collectors.Joining
- Collectors.PartitioningBy
- Collectors.PartitioningBySlice
- Collectors.SummarizingInt
- Collectors.ToList
- Collectors.ToMap
- Collectors.ToSet
- Stream
- Stream.AllMatch
- Stream.AnyMatch
- Stream.Collect
- Stream.Distinct
- Stream.DistinctBy
- Stream.DropWhile
- Stream.Filter
- Stream.FindFirst
- Stream.FlatMap
- Stream.From
- Stream.FromCollection
- Stream.FromConcat
- Stream.FromEmpty
- Stream.FromRange
- Stream.FromRangeClosed
- Stream.FromSlice
- Stream.Limit
- Stream.Map
- Stream.Max
- Stream.Min
- Stream.NoneMatch
- Stream.OnClose
- Stream.Parallel
- Stream.Peek
- Stream.ReduceWithIdentity
- Stream.ReduceWithInitial
- Stream.Skip
- Stream.Sorted
- Stream.SortedBy
- Stream.TakeWhile
- Stream.ToSlice
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Collector ¶
type Collector[T, A, R any] struct { Supplier func() A Accumulator func(A, T) A Combiner func(A, A) A Finisher func(A) R }
Collector is a mutable reduction operation that accumulates input elements into a mutable result container, optionally transforming the accumulated result into a final representation after all input elements have been processed.
T is the type of input elements to the reduction. A is the mutable accumulation type of the reduction. R is the result type of the reduction.
func NewCollector ¶
func NewCollector[T, A, R any](supplier func() A, accumulator func(A, T) A, combiner func(A, A) A, finisher func(A) R) Collector[T, A, R]
NewCollector constructs a new Collector with the specified supplier, accumulator, combiner, and finisher.
func NewSimpleCollector ¶
func NewSimpleCollector[T, R any](supplier func() R, accumulator func(R, T) R, combiner ...func(R, R) R) Collector[T, R, R]
NewSimpleCollector constructs a Collector where the intermediate accumulation type and final result type are identical, using an identity finisher.
type Collectors ¶
type Collectors struct{}
Collectors provides static factory methods for standard Collector implementations, mirroring Java 8's java.util.stream.Collectors.
func (Collectors) AveragingFloat64 ¶
func (Collectors) AveragingFloat64[T any](mapper func(T) float64) Collector[T, *avgAcc, float64]
AveragingFloat64 returns a Collector that produces the arithmetic mean of a float64-valued function applied to input elements.
func (Collectors) AveragingInt ¶
func (Collectors) AveragingInt[T any](mapper func(T) int) Collector[T, *avgAcc, float64]
AveragingInt returns a Collector that produces the arithmetic mean of an integer-valued function applied to input elements.
func (Collectors) Counting ¶
func (Collectors) Counting[T any]() Collector[T, *int64, int64]
Counting returns a Collector that counts the number of input elements.
Example ¶
ExampleCollectors_Counting demonstrates counting elements with a collector.
count := streamOf("one", "two", "three").Collect(
Collectors{}.Counting[string](),
)
fmt.Println(count)
Output: 3
func (Collectors) Filtering ¶
func (Collectors) Filtering[T, A, R any](predicate func(T) bool, downstream Collector[T, A, R]) Collector[T, A, R]
Filtering adapts a Collector to one accepting elements of the same type T by applying the predicate and accumulating only elements that match.
func (Collectors) FlatMapping ¶
func (Collectors) FlatMapping[T, U, A, R any](mapper func(T) []U, downstream Collector[U, A, R]) Collector[T, A, R]
FlatMapping adapts a Collector accepting elements of type U to one accepting elements of type T by applying a flat-mapping function that maps each input element to a slice of U before accumulation.
func (Collectors) GroupingBy ¶
func (Collectors) GroupingBy[T any, K comparable, A, D any](classifier func(T) K, downstream Collector[T, A, D]) Collector[T, map[K]A, map[K]D]
GroupingBy returns a Collector implementing a "group by" operation on input elements of type T, grouping elements according to a classification function, and performing a downstream reduction on the elements associated with a given key.
Example ¶
ExampleCollectors_GroupingBy demonstrates counting words grouped by their first letter.
words := []string{"apple", "apricot", "banana", "cherry", "cranberry"}
counts := streamOfSlice(words).Collect(
Collectors{}.GroupingBy(
func(w string) string { return string(w[0]) },
Collectors{}.Counting[string](),
),
)
fmt.Println(counts["a"])
fmt.Println(counts["b"])
fmt.Println(counts["c"])
Output: 2 1 2
func (Collectors) GroupingBySlice ¶
func (this Collectors) GroupingBySlice[T any, K comparable](classifier func(T) K) Collector[T, map[K][]T, map[K][]T]
GroupingBySlice returns a Collector that groups elements by key into slices of elements.
Example ¶
ExampleCollectors_GroupingBySlice demonstrates grouping employees into slices by department.
type Employee struct {
Name string
Dept string
}
employees := []Employee{
{Name: "Alice", Dept: "Engineering"},
{Name: "Bob", Dept: "Sales"},
{Name: "Charlie", Dept: "Engineering"},
}
byDept := streamOfSlice(employees).Collect(
Collectors{}.GroupingBySlice(func(e Employee) string { return e.Dept }),
)
fmt.Println(len(byDept["Engineering"]))
fmt.Println(len(byDept["Sales"]))
Output: 2 1
func (Collectors) Joining ¶
func (Collectors) Joining(delimiter string, prefixAndSuffix ...string) Collector[string, *joinAcc, string]
Joining returns a Collector that concatenates input strings, separated by the specified delimiter, with an optional prefix and suffix.
Example ¶
ExampleCollectors_Joining demonstrates joining names with a delimiter, prefix, and suffix.
joined := streamOf("Alice", "Bob", "Charlie").
Collect(Collectors{}.Joining(", ", "[", "]"))
fmt.Println(joined)
Output: [Alice, Bob, Charlie]
func (Collectors) Mapping ¶
func (Collectors) Mapping[T, U, A, R any](mapper func(T) U, downstream Collector[U, A, R]) Collector[T, A, R]
Mapping adapts a Collector accepting elements of type U to one accepting elements of type T by applying a mapping function to each input element before accumulation.
func (Collectors) MaxBy ¶
func (Collectors) MaxBy[T any](comparator func(a, b T) int) Collector[T, *Optional[T], Optional[T]]
MaxBy returns a Collector that produces the maximal element according to a given comparator, described as an Optional[T].
func (Collectors) MinBy ¶
func (Collectors) MinBy[T any](comparator func(a, b T) int) Collector[T, *Optional[T], Optional[T]]
MinBy returns a Collector that produces the minimal element according to a given comparator, described as an Optional[T].
func (Collectors) PartitioningBy ¶
func (Collectors) PartitioningBy[T, A, D any](predicate func(T) bool, downstream Collector[T, A, D]) Collector[T, map[bool]A, map[bool]D]
PartitioningBy returns a Collector which partitions the input elements according to a Predicate, and organizes them into a map[bool]D via a downstream collector.
Example ¶
ExampleCollectors_PartitioningBy demonstrates counting passing and failing grades.
grades := []int{45, 78, 92, 55, 88}
counts := streamOfSlice(grades).Collect(
Collectors{}.PartitioningBy(
func(grade int) bool { return grade >= 60 },
Collectors{}.Counting[int](),
),
)
fmt.Println("Passed:", counts[true])
fmt.Println("Failed:", counts[false])
Output: Passed: 3 Failed: 2
func (Collectors) PartitioningBySlice ¶
func (this Collectors) PartitioningBySlice[T any](predicate func(T) bool) Collector[T, map[bool][]T, map[bool][]T]
PartitioningBySlice returns a Collector which partitions the input elements according to a Predicate into two slices: map[true][]T and map[false][]T.
Example ¶
ExampleCollectors_PartitioningBySlice demonstrates partitioning numbers into even and odd slices.
partitioned := streamOf(1, 2, 3, 4, 5, 6).Collect(
Collectors{}.PartitioningBySlice(func(n int) bool { return n%2 == 0 }),
)
fmt.Println(partitioned[true])
fmt.Println(partitioned[false])
Output: [2 4 6] [1 3 5]
func (Collectors) Reducing ¶
func (Collectors) Reducing[T any](identity T, op func(T, T) T) Collector[T, *T, T]
Reducing returns a Collector which performs a reduction of its input elements under a specified identity and associative BinaryOperator.
func (Collectors) SummarizingFloat64 ¶
func (Collectors) SummarizingFloat64[T any](mapper func(T) float64) Collector[T, *Float64SummaryStatistics, Float64SummaryStatistics]
SummarizingFloat64 returns a Collector that computes summary statistics on a float64-valued function applied to input elements.
func (Collectors) SummarizingInt ¶
func (Collectors) SummarizingInt[T any](mapper func(T) int) Collector[T, *IntSummaryStatistics, IntSummaryStatistics]
SummarizingInt returns a Collector that computes summary statistics on an integer-valued function applied to input elements.
Example ¶
ExampleCollectors_SummarizingInt demonstrates collecting count, sum, extrema, and average.
stats := streamOf(10, 20, 30, 40).Collect(
Collectors{}.SummarizingInt(func(n int) int { return n }),
)
fmt.Printf("Count=%d, Sum=%d, Min=%d, Max=%d, Avg=%.1f\n",
stats.Count, stats.Sum, stats.Min, stats.Max, stats.Average())
Output: Count=4, Sum=100, Min=10, Max=40, Avg=25.0
func (Collectors) SummingFloat64 ¶
SummingFloat64 returns a Collector that produces the sum of a float64-valued function applied to input elements.
func (Collectors) SummingInt ¶
SummingInt returns a Collector that produces the sum of an integer-valued function applied to input elements.
func (Collectors) ToList ¶
func (Collectors) ToList[T any]() Collector[T, List[T], List[T]]
ToList returns a Collector that accumulates input elements into a List[T].
Example ¶
ExampleCollectors_ToList demonstrates collecting filtered even numbers into a list.
evens := streamOf(1, 2, 3, 4).
Filter(func(n int) bool { return n%2 == 0 }).
Collect(Collectors{}.ToList[int]())
fmt.Println(evens.ToSlice())
Output: [2 4]
func (Collectors) ToMap ¶
func (Collectors) ToMap[T any, K comparable, V any](keyMapper func(T) K, valueMapper func(T) V, mergeRule ...func(existing, newVal V) V) Collector[T, map[K]V, map[K]V]
ToMap returns a Collector that accumulates elements into a map whose keys and values are the result of applying the provided mapping functions to the input elements.
If duplicate keys are encountered, mergeRule (if provided) is invoked to resolve the collision. If no mergeRule is provided, duplicate keys trigger an IllegalStateError.
Example ¶
ExampleCollectors_ToMap demonstrates collecting city names into a map keyed by city code.
type City struct {
Code string
Name string
}
cities := []City{
{Code: "NYC", Name: "New York City"},
{Code: "PAR", Name: "Paris"},
{Code: "LON", Name: "London"},
}
cityMap := streamOfSlice(cities).Collect(
Collectors{}.ToMap(
func(c City) string { return c.Code },
func(c City) string { return c.Name },
),
)
fmt.Println(cityMap["PAR"])
fmt.Println(cityMap["NYC"])
Output: Paris New York City
func (Collectors) ToSet ¶
func (Collectors) ToSet[T comparable]() Collector[T, Set[T], Set[T]]
ToSet returns a Collector that accumulates unique input elements into a Set[T].
Example ¶
ExampleCollectors_ToSet demonstrates collecting unique strings into a set.
set := streamOf("apple", "banana", "apple", "cherry").
Collect(Collectors{}.ToSet[string]())
fmt.Println(set.Contains("apple"))
fmt.Println(set.Contains("banana"))
fmt.Println(set.Size())
Output: true true 3
func (Collectors) ToSetSlice ¶
func (Collectors) ToSetSlice[T comparable]() Collector[T, map[T]struct{}, []T]
ToSetSlice returns a Collector that accumulates unique elements into a slice.
func (Collectors) ToSlice ¶
func (Collectors) ToSlice[T any]() Collector[T, []T, []T]
ToSlice returns a Collector that accumulates input elements into a new slice.
type Float64SummaryStatistics ¶
Float64SummaryStatistics is a state object for collecting statistics such as count, min, max, sum, and average.
func NewFloat64SummaryStatistics ¶
func NewFloat64SummaryStatistics() *Float64SummaryStatistics
NewFloat64SummaryStatistics constructs an empty instance with zero count, zero sum, math.MaxFloat64 min, and -math.MaxFloat64 max.
func (*Float64SummaryStatistics) Accept ¶
func (this *Float64SummaryStatistics) Accept(value float64)
Accept records a new float64 value into the summary information.
func (*Float64SummaryStatistics) Average ¶
func (this *Float64SummaryStatistics) Average() float64
Average returns the arithmetic mean of values recorded, or zero if no values have been recorded.
func (*Float64SummaryStatistics) Combine ¶
func (this *Float64SummaryStatistics) Combine(other *Float64SummaryStatistics)
Combine combines the state of another Float64SummaryStatistics into this one.
func (*Float64SummaryStatistics) String ¶
func (this *Float64SummaryStatistics) String() string
String returns a string representation of the statistics.
type IntSummaryStatistics ¶
IntSummaryStatistics is a state object for collecting statistics such as count, min, max, sum, and average.
func NewIntSummaryStatistics ¶
func NewIntSummaryStatistics() *IntSummaryStatistics
NewIntSummaryStatistics constructs an empty instance with zero count, zero sum, math.MaxInt min, and math.MinInt max.
func (*IntSummaryStatistics) Accept ¶
func (this *IntSummaryStatistics) Accept(value int)
Accept records a new int value into the summary information.
func (*IntSummaryStatistics) Average ¶
func (this *IntSummaryStatistics) Average() float64
Average returns the arithmetic mean of values recorded, or zero if no values have been recorded.
func (*IntSummaryStatistics) Combine ¶
func (this *IntSummaryStatistics) Combine(other *IntSummaryStatistics)
Combine combines the state of another IntSummaryStatistics into this one.
func (*IntSummaryStatistics) String ¶
func (this *IntSummaryStatistics) String() string
String returns a string representation of the statistics.
type Stream ¶
type Stream[T any] struct { // contains filtered or unexported fields }
Stream represents a lazy, potentially parallel sequence of elements supporting aggregate operations. Stream operations are divided into intermediate operations (which return a new Stream) and terminal operations (which consume the stream and produce a result or a side-effect).
Streams are single-use: once a terminal operation has been executed, or an intermediate operation has linked this stream into a new pipeline stage, the stream is considered consumed and cannot be reused.
Example ¶
ExampleStream demonstrates filtering, sorting, and joining language names.
// Process a sequence of names: filter, sort by length, and join.
result := Stream[string]{}.From("Go", "Python", "Rust", "TypeScript").
Filter(func(s string) bool { return len(s) > 2 }).
SortedBy(func(s string) int { return len(s) }).
Collect(Collectors{}.Joining(", "))
fmt.Println(result)
Output: Rust, Python, TypeScript
func (Stream[T]) AllMatch ¶
AllMatch returns whether all elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty, true is returned and the predicate is not evaluated.
Example ¶
ExampleStream_AllMatch demonstrates testing whether every number is positive.
allPositive := Stream[int]{}.From(1, 2, 3).
AllMatch(func(n int) bool { return n > 0 })
fmt.Println(allPositive)
Output: true
func (Stream[T]) AnyMatch ¶
AnyMatch returns whether any elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result.
Example ¶
ExampleStream_AnyMatch demonstrates testing whether a stream contains an even number.
hasEven := Stream[int]{}.From(1, 3, 5, 6, 7).
AnyMatch(func(n int) bool { return n%2 == 0 })
fmt.Println(hasEven)
Output: true
func (Stream[T]) Close ¶
func (this Stream[T]) Close()
Close closes this stream, executing all registered close handlers. Calling Close is idempotent: handlers are executed at most once.
func (Stream[T]) Collect ¶
Collect performs a mutable reduction operation on the elements of this stream using a Collector. If the stream is parallel and the collector has a Combiner, collection will be performed concurrently across goroutines. Note: This method leverages Go 1.27's type parameters on struct methods.
Example ¶
ExampleStream_Collect demonstrates collecting stream elements into a list.
list := streamOf(1, 2, 3).
Collect(Collectors{}.ToList[int]())
fmt.Println(list.ToSlice())
Output: [1 2 3]
func (Stream[T]) CollectWith ¶
func (this Stream[T]) CollectWith[R any](supplier func() R, accumulator func(R, T) R, combiner ...func(R, R) R) R
CollectWith is a convenience method that accumulates elements into a result container using the provided supplier, accumulator, and optional combiner functions. Note: This method leverages Go 1.27's type parameters on struct methods.
func (Stream[T]) Distinct ¶
Distinct returns a stream consisting of the distinct elements of this stream. For comparable types, deduplication uses hash set lookup. For non-comparable types (e.g. slices), it safely falls back to deep equality checks.
Example ¶
ExampleStream_Distinct demonstrates removing duplicate integers.
items := Stream[int]{}.From(1, 2, 2, 3, 1, 4).
Distinct().
ToSlice()
fmt.Println(items)
Output: [1 2 3 4]
func (Stream[T]) DistinctBy ¶
func (this Stream[T]) DistinctBy[K comparable](keySelector func(T) K) Stream[T]
DistinctBy returns a stream consisting of distinct elements according to the key returned by keySelector. Note: This method leverages Go 1.27's type parameters on struct methods.
Example ¶
ExampleStream_DistinctBy demonstrates retaining the first person for each unique ID.
type Person struct {
Name string
ID int
}
people := Stream[Person]{}.From(
Person{Name: "Alice", ID: 1},
Person{Name: "Bob", ID: 2},
Person{Name: "Alice Duplicate", ID: 1},
).DistinctBy(func(p Person) int { return p.ID }).
Map(func(p Person) string { return p.Name }).
ToSlice()
fmt.Println(people)
Output: [Alice Bob]
func (Stream[T]) DropWhile ¶
DropWhile returns a stream consisting of the remaining elements of this stream after dropping the longest prefix of elements that match the given predicate.
Example ¶
ExampleStream_DropWhile demonstrates skipping elements until a predicate first fails.
dropped := Stream[int]{}.From(1, 2, 3, 10, 4, 5).
DropWhile(func(n int) bool { return n < 5 }).
ToSlice()
fmt.Println(dropped)
Output: [10 4 5]
func (Stream[T]) Filter ¶
Filter returns a stream consisting of the elements of this stream that match the given predicate.
Example ¶
ExampleStream_Filter demonstrates retaining words that match a length predicate.
words := Stream[string]{}.From("cat", "elephant", "dog", "bear").
Filter(func(w string) bool { return len(w) > 3 }).
ToSlice()
fmt.Println(words)
Output: [elephant bear]
func (Stream[T]) FindAny ¶
func (this Stream[T]) FindAny() Optional[T]
FindAny returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. In parallel streams, returns whichever element is evaluated first by any goroutine.
func (Stream[T]) FindFirst ¶
func (this Stream[T]) FindFirst() Optional[T]
FindFirst returns an Optional describing the first element of this stream in encounter order, or an empty Optional if the stream is empty.
Example ¶
ExampleStream_FindFirst demonstrates finding the first word that matches a filter.
match := Stream[string]{}.From("cat", "elephant", "dog").
Filter(func(s string) bool { return len(s) > 3 }).
FindFirst()
if val, ok := match.Get(); ok {
fmt.Println(val)
}
Output: elephant
func (Stream[T]) FlatMap ¶
FlatMap returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream. Each mapped stream is automatically closed after its contents have been placed into this stream. Note: This method leverages Go 1.27's type parameters on struct methods.
Example ¶
ExampleStream_FlatMap demonstrates flattening character streams from strings.
pairs := Stream[string]{}.From("ab", "cd").
FlatMap(func(s string) Stream[rune] {
return Stream[rune]{}.FromSlice([]rune(s))
}).
Map(func(r rune) string { return string(r) }).
ToSlice()
fmt.Println(pairs)
Output: [a b c d]
func (Stream[T]) FlatMapSeq ¶
FlatMapSeq returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped Go iterator sequence. Note: This method leverages Go 1.27's type parameters on struct methods.
func (Stream[T]) FlatMapSlice ¶
FlatMapSlice returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped slice. Note: This method leverages Go 1.27's type parameters on struct methods.
func (Stream[T]) ForEach ¶
func (this Stream[T]) ForEach(action func(T))
ForEach performs an action for each element of this stream. If the stream is parallel, the action is executed concurrently across goroutines; the order of execution is not guaranteed.
func (Stream[T]) ForEachOrdered ¶
func (this Stream[T]) ForEachOrdered(action func(T))
ForEachOrdered performs an action for each element of this stream, in the encounter order of the stream.
func (Stream[T]) From ¶
From returns a sequential Stream containing the specified elements.
Example ¶
ExampleStream_From demonstrates creating and consuming a stream of explicit values.
Stream[string]{}.From("Go", "Java", "Rust").
ForEach(func(lang string) {
fmt.Println(lang)
})
Output: Go Java Rust
func (Stream[T]) FromChan ¶
FromChan returns a sequential Stream whose elements are read from the specified channel until the channel is closed.
func (Stream[T]) FromCollection ¶
FromCollection returns a sequential Stream whose source is the specified collection.
Example ¶
ExampleStream_FromCollection demonstrates filtering elements from a collection.
list := Stream[string]{}.From("apple", "banana", "cherry").
Collect(Collectors{}.ToList[string]())
count := Stream[string]{}.FromCollection(list).
Filter(func(s string) bool { return len(s) > 5 }).
Count()
fmt.Println(count)
Output: 2
func (Stream[T]) FromConcat ¶
FromConcat creates a lazily concatenated Stream whose elements are all the elements of the first stream followed by all the elements of the second stream.
Example ¶
ExampleStream_FromConcat demonstrates concatenating two streams in encounter order.
s1 := Stream[int]{}.From(1, 2)
s2 := Stream[int]{}.From(3, 4)
combined := Stream[int]{}.FromConcat(s1, s2).ToSlice()
fmt.Println(combined)
Output: [1 2 3 4]
func (Stream[T]) FromEmpty ¶
FromEmpty returns an empty sequential Stream.
Example ¶
ExampleStream_FromEmpty demonstrates creating an empty stream with zero elements.
empty := Stream[int]{}.FromEmpty()
fmt.Println(empty.Count())
Output: 0
func (Stream[T]) FromGenerate ¶
FromGenerate returns an infinite sequential unordered Stream where each element is generated by the provided supplier function.
func (Stream[T]) FromIterate ¶
FromIterate returns an infinite sequential ordered Stream produced by iterative application of a function to an initial element seed: seed, f(seed), f(f(seed)), ...
func (Stream[T]) FromIterateWithPredicate ¶
FromIterateWithPredicate returns a sequential ordered Stream produced by iterative application of a function to an initial element seed, conditioned on satisfying the specified hasNext predicate.
func (Stream[T]) FromRange ¶
FromRange returns a sequential ordered Stream from startInclusive (inclusive) to endExclusive (exclusive) by an incremental step of 1.
Example ¶
ExampleStream_FromRange demonstrates filtering a range with an exclusive upper bound.
evens := Stream[int]{}.FromRange(0, 6).
Filter(func(n int) bool { return n%2 == 0 }).
ToSlice()
fmt.Println(evens)
Output: [0 2 4]
func (Stream[T]) FromRangeClosed ¶
FromRangeClosed returns a sequential ordered Stream from startInclusive (inclusive) to endInclusive (inclusive) by an incremental step of 1.
Example ¶
ExampleStream_FromRangeClosed demonstrates summing a range with an inclusive upper bound.
sum := Stream[int]{}.FromRangeClosed(1, 5).
ReduceWithIdentity(0, func(a, b int) int { return a + b })
fmt.Println(sum)
Output: 15
func (Stream[T]) FromSeq ¶
FromSeq returns a sequential Stream whose source is the given Go iterator sequence (iter.Seq[T]).
func (Stream[T]) FromSlice ¶
FromSlice returns a sequential Stream whose source is the specified slice.
Example ¶
ExampleStream_FromSlice demonstrates counting elements from a slice.
words := []string{"hello", "world"}
count := Stream[string]{}.FromSlice(words).Count()
fmt.Println(count)
Output: 2
func (Stream[T]) IsParallel ¶
IsParallel returns whether this stream would execute terminal operations in parallel.
func (Stream[T]) Limit ¶
Limit returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.
Example ¶
ExampleStream_Limit demonstrates retaining only the first three elements.
firstThree := Stream[int]{}.FromRange(1, 100).
Limit(3).
ToSlice()
fmt.Println(firstThree)
Output: [1 2 3]
func (Stream[T]) Map ¶
Map returns a stream consisting of the results of applying the given function to the elements of this stream. Note: This method leverages Go 1.27's type parameters on struct methods.
Example ¶
ExampleStream_Map demonstrates mapping strings to their lengths.
lengths := Stream[string]{}.From("one", "three", "six").
Map(func(s string) int { return len(s) }).
ToSlice()
fmt.Println(lengths)
Output: [3 5 3]
func (Stream[T]) Max ¶
Max returns the maximum element of this stream according to the provided comparator (or natural ordering if no comparator is passed).
Example ¶
ExampleStream_Max demonstrates finding the largest integer in a stream.
maxVal := Stream[int]{}.From(5, 2, 8, 1, 9).Max()
if val, ok := maxVal.Get(); ok {
fmt.Println(val)
}
Output: 9
func (Stream[T]) MaxBy ¶
func (this Stream[T]) MaxBy[K OrderedConstraint](keySelector func(T) K) Optional[T]
MaxBy returns the maximum element of this stream according to the key returned by keySelector. Note: This method leverages Go 1.27's type parameters on struct methods.
func (Stream[T]) Min ¶
Min returns the minimum element of this stream according to the provided comparator (or natural ordering if no comparator is passed).
Example ¶
ExampleStream_Min demonstrates finding the smallest integer in a stream.
minVal := Stream[int]{}.From(5, 2, 8, 1, 9).Min()
if val, ok := minVal.Get(); ok {
fmt.Println(val)
}
Output: 1
func (Stream[T]) MinBy ¶
func (this Stream[T]) MinBy[K OrderedConstraint](keySelector func(T) K) Optional[T]
MinBy returns the minimum element of this stream according to the key returned by keySelector. Note: This method leverages Go 1.27's type parameters on struct methods.
func (Stream[T]) NoneMatch ¶
NoneMatch returns whether no elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty, true is returned and the predicate is not evaluated.
Example ¶
ExampleStream_NoneMatch demonstrates testing whether no numbers are negative.
noneNegative := Stream[int]{}.From(1, 2, 3).
NoneMatch(func(n int) bool { return n < 0 })
fmt.Println(noneNegative)
Output: true
func (Stream[T]) OnClose ¶
OnClose returns an equivalent stream with an additional close handler. Close handlers are run when the Close() method is called on the stream.
Example ¶
ExampleStream_OnClose demonstrates running a close handler after stream consumption.
stream := Stream[int]{}.From(1, 2, 3).OnClose(func() {
fmt.Println("stream closed")
})
_ = stream.ToSlice()
Output: stream closed
func (Stream[T]) Parallel ¶
Parallel returns an equivalent stream that is parallel.
Example ¶
ExampleStream_Parallel demonstrates filtering and counting a stream marked for parallel execution.
count := Stream[int]{}.FromRangeClosed(1, 100).
Parallel().
Filter(func(n int) bool { return n%2 == 0 }).
Count()
fmt.Println(count)
Output: 50
func (Stream[T]) Peek ¶
Peek returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.
Example ¶
ExampleStream_Peek demonstrates observing elements as a pipeline consumes them.
var logged []int
res := Stream[int]{}.From(1, 2, 3).
Peek(func(n int) { logged = append(logged, n) }).
Map(func(n int) int { return n * 10 }).
ToSlice()
fmt.Println("Result:", res)
fmt.Println("Logged:", logged)
Output: Result: [10 20 30] Logged: [1 2 3]
func (Stream[T]) Reduce ¶
func (this Stream[T]) Reduce(accumulator func(a, b T) T) Optional[T]
Reduce performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any.
func (Stream[T]) ReduceWithIdentity ¶
func (this Stream[T]) ReduceWithIdentity(identity T, accumulator func(a, b T) T) T
ReduceWithIdentity performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value.
Example ¶
ExampleStream_ReduceWithIdentity demonstrates multiplying numbers with an identity of one.
product := Stream[int]{}.From(2, 3, 4).
ReduceWithIdentity(1, func(a, b int) int { return a * b })
fmt.Println(product)
Output: 24
func (Stream[T]) ReduceWithInitial ¶
ReduceWithInitial performs a reduction on the elements of this stream, starting from an initial value of type R and accumulating elements of type T into R. Note: This method leverages Go 1.27's type parameters on struct methods.
Example ¶
ExampleStream_ReduceWithInitial demonstrates reducing integers into a string result.
res := Stream[int]{}.From(1, 2, 3).
ReduceWithInitial("Numbers:", func(acc string, n int) string {
return fmt.Sprintf("%s %d", acc, n)
})
fmt.Println(res)
Output: Numbers: 1 2 3
func (Stream[T]) Seq ¶
Seq returns an iter.Seq[T] iterator over the elements of this stream. The stream is marked as consumed, and closing is automatically handled when iteration finishes.
func (Stream[T]) Sequential ¶
Sequential returns an equivalent stream that is sequential.
func (Stream[T]) Skip ¶
Skip returns a stream consisting of the remaining elements of this stream after discarding the first n elements.
Example ¶
ExampleStream_Skip demonstrates discarding the first two elements.
afterTwo := Stream[int]{}.From(10, 20, 30, 40).
Skip(2).
ToSlice()
fmt.Println(afterTwo)
Output: [30 40]
func (Stream[T]) Sorted ¶
Sorted returns a stream consisting of the elements of this stream, sorted according to natural order or the provided comparator function (which returns negative if a < b, 0 if a == b, and positive if a > b).
If no comparator is supplied and the elements are not naturally ordered, an IllegalArgumentError is raised.
Example ¶
ExampleStream_Sorted demonstrates sorting integers in natural order.
sorted := Stream[int]{}.From(4, 1, 3, 2).
Sorted().
ToSlice()
fmt.Println(sorted)
Output: [1 2 3 4]
func (Stream[T]) SortedBy ¶
SortedBy returns a stream consisting of the elements of this stream, sorted in ascending order by the key returned from the keySelector function. Note: This method leverages Go 1.27's type parameters on struct methods.
Example ¶
ExampleStream_SortedBy demonstrates sorting products by ascending price.
type Product struct {
Name string
Price int
}
sorted := Stream[Product]{}.From(
Product{Name: "Book", Price: 15},
Product{Name: "Pen", Price: 3},
Product{Name: "Bag", Price: 40},
).SortedBy(func(p Product) int { return p.Price }).
Map(func(p Product) string { return p.Name }).
ToSlice()
fmt.Println(sorted)
Output: [Pen Book Bag]
func (Stream[T]) SortedByDesc ¶
SortedByDesc returns a stream consisting of the elements of this stream, sorted in descending order by the key returned from the keySelector function. Note: This method leverages Go 1.27's type parameters on struct methods.
func (Stream[T]) SortedFunc ¶
SortedFunc returns a stream consisting of the elements of this stream, sorted according to the provided less function.
func (Stream[T]) TakeWhile ¶
TakeWhile returns a stream consisting of the longest prefix of elements of this stream that match the given predicate.
Example ¶
ExampleStream_TakeWhile demonstrates taking elements until a predicate first fails.
taken := Stream[int]{}.From(1, 2, 3, 10, 4, 5).
TakeWhile(func(n int) bool { return n < 5 }).
ToSlice()
fmt.Println(taken)
Output: [1 2 3]
func (Stream[T]) ToSlice ¶
func (this Stream[T]) ToSlice() []T
ToSlice returns a slice containing the elements of this stream in encounter order.
Example ¶
ExampleStream_ToSlice demonstrates collecting stream elements into a slice.
slice := Stream[string]{}.From("a", "b", "c").ToSlice()
fmt.Println(slice)
Output: [a b c]