stream

package
v1.1.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 7, 2024 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Overview

Package stream provides an abstraction for working with a stream of values supporting sequential computational operations. 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. It is inspired by Java's `Stream` class, but uses functional composition, rather than fluent-style chaining.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Aggregate

func Aggregate[E, A, F any](s Stream[E], identity A, accumulate Accumulator[A, E], finish Finisher[A, F]) F

Aggregate combines the elements of the stream into a single value using the given identity value, accumulator function and finisher function. The accumulated value is initialized to the identity value. The accumulator function is used to combine each element with the accumulated value. The finisher function is used to compute the final result after all elements have been accumulated. The stream is fully consumed.

Example usage:

s := stream.Aggregate(
  stream.Of(1, 2, 3),
  0,                 // Initial value
  func(a, e int) int {
    return a + e     // Accumulate with addition
  },
  func(a int) int {
    return a * 2     // Finish with multiplication by 2
  },
) // (1+2+3) * 2 = 12

func AllMatch

func AllMatch[E any](s Stream[E], p Predicate[E]) (allMatch bool)

AllMatch returns true if all elements in the stream match the given Predicate. If the stream is empty, it returns false.

Example usage:

out := stream.AllMatch(stream.Of(1, 2, 3), pred.GreaterThan(0)) // true
out = stream.AllMatch(stream.Of(1, 2, 3), pred.GreaterThan(1)) // false

func AnyMatch

func AnyMatch[E any](s Stream[E], p Predicate[E]) (anyMatch bool)

AnyMatch returns true if any element in the stream matches the given Predicate. If the stream is empty, it returns false.

Example usage:

out := stream.AnyMatch(stream.Of(1, 2, 3), pred.GreaterThan(2)) // true
out = stream.AnyMatch(stream.Of(1, 2, 3), pred.GreaterThan(3)) // false

func Average

func Average[E constraint.RealNumber](s Stream[E]) float64

Average computes the average of all elements in the stream of any number type E and returns the result as type float64. The result of an empty stream is the zero value of type float64. The stream is fully consumed.

Example usage:

n := stream.Average(stream.Of(1, 2, 3)) // 2.0 (float64)

func CollectChannel

func CollectChannel[E any](s Stream[E], ch chan<- E)

CollectChannel sends all elements from the stream to the given channel. The channel must be buffered or have a receiver ready to receive the elements in another goroutine. The method returns when the stream is exhausted and all elements have been sent to the channel.

Example usage:

ch := make(chan int, 3)
go func() {
  for e := range ch {
    fmt.Println(e)
  }
}()
stream.CollectChannel(stream.Of(1, 2, 3), ch)
close(ch)

Output:

1
2
3

func CollectChannelAsync

func CollectChannelAsync[E any](s Stream[E], buf int) <-chan E

CollectChannelAsync sends all elements from the stream to a new channel returned by the method. A goroutine is started to send the elements to the channel and the method returns immediately. The caller must ensure the channel is fully consumed, otherwise the goroutine will be blocked forever. The channel is buffered with the given buffer size, and is closed when the stream is exhausted.

Example usage:

ch := stream.CollectChannelAsync(stream.Of(1, 2, 3), 3)
for e := range ch {
  fmt.Println(e)
}

Output:

1
2
3

func CollectChannelAsyncCtx

func CollectChannelAsyncCtx[E any](ctx context.Context, s Stream[E], buf int) <-chan E

CollectChannelAsyncCtx behaves like CollectChannelAsync, but consumption of the stream stops when the context is done. The caller can assume the channel will eventually close when the context is done.

Example usage:

ctx := context.Background()
ch := stream.CollectChannelAsyncCtx(ctx, stream.Of(1, 2, 3), 3)
for e := range ch {
  fmt.Println(e)
}

Output:

1
2
3

func CollectChannelCtx

func CollectChannelCtx[E any](ctx context.Context, s Stream[E], ch chan<- E)

CollectChannelCtx behaves like CollectChannel, but it returns immediately when the context is done.

Example usage:

ch := make(chan int, 3)
go func() {
  for e := range ch {
    fmt.Println(e)
  }
}()
ctx := context.Background()
stream.CollectChannelCtx(ctx, stream.Of(1, 2, 3), ch)
close(ch)

Output:

1
2
3

func CollectMap

func CollectMap[K comparable, V any](s Stream[pair.Pair[K, V]]) map[K]V

CollectMap returns a map containing all key-value pair elements from the stream. The stream is fully consumed.

Example usage:

s := stream.CollectMap(stream.Of(pair.Of(1, "foo"), pair.Of(2, "bar"))) // map[int]string{1: "foo", 2: "bar"}

func CollectSlice

func CollectSlice[E any](s Stream[E]) []E

CollectSlice returns a slice containing all elements from the stream. The stream is fully consumed.

Example usage:

s := stream.CollectSlice(stream.Of(1, 2, 3)) // []int{1, 2, 3}

func Contains

func Contains[E comparable](s Stream[E], e E) bool

Contains returns true if the stream contains the given element; false otherwise. The element type E must be comparable.

Example usage:

out := stream.Contains(stream.Of(1, 2, 3), 2) // true
out = stream.Contains(stream.Of(1, 2, 3), 4) // false

func ContainsAll

func ContainsAll[E comparable](s Stream[E], es ...E) bool

ContainsAll returns true if the stream contains all the given elements; false otherwise. The element type E must be comparable.

Example usage:

out := stream.ContainsAll(stream.Of(1, 2, 3), 2, 3) // true
out = stream.ContainsAll(stream.Of(1, 2, 3), 2, 4) // false

func ContainsAllBy

func ContainsAllBy[E any](s Stream[E], compare cmp.Comparer[E], es ...E) bool

ContainsAllBy returns true if the stream contains all the given elements; false otherwise. The elements are compared using the given cmp.Comparer.

Example usage:

out := stream.ContainsAllBy(stream.Of(1, 2, 3), cmp.Natural[int](), 2, 3) // true
out = stream.ContainsAllBy(stream.Of(1, 2, 3), cmp.Natural[int](), 2, 4) // false

func ContainsAny

func ContainsAny[E comparable](s Stream[E], es ...E) bool

ContainsAny returns true if the stream contains any of the given elements; false otherwise. The element type E must be comparable.

Example usage:

out := stream.ContainsAny(stream.Of(1, 2, 3), 2, 4) // true
out = stream.ContainsAny(stream.Of(1, 2, 3), 4, 5) // false

func ContainsAnyBy

func ContainsAnyBy[E any](s Stream[E], compare cmp.Comparer[E], es ...E) bool

ContainsAnyBy returns true if the stream contains any of the given elements; false otherwise. The elements are compared using the given cmp.Comparer.

Example usage:

out := stream.ContainsAnyBy(stream.Of(1, 2, 3), cmp.Natural[int](), 2, 4) // true
out = stream.ContainsAnyBy(stream.Of(1, 2, 3), cmp.Natural[int](), 4, 5) // false

func ContainsBy

func ContainsBy[E any](s Stream[E], compare cmp.Comparer[E], e E) bool

ContainsBy returns true if the stream contains the given element; false otherwise. The elements are compared using the given cmp.Comparer.

Example usage:

out := stream.ContainsBy(stream.Of(1, 2, 3), 2, cmp.Natural[int]()) // true
out = stream.ContainsBy(stream.Of(1, 2, 3), 4, cmp.Natural[int]()) // false

func ContainsNone

func ContainsNone[E comparable](s Stream[E], es ...E) bool

ContainsNone returns true if the stream contains none of the given elements; false otherwise. The element type E must be comparable.

Example usage:

out := stream.ContainsNone(stream.Of(1, 2, 3), 4, 5) // true
out = stream.ContainsNone(stream.Of(1, 2, 3), 2, 4) // false

func ContainsNoneBy

func ContainsNoneBy[E any](s Stream[E], compare cmp.Comparer[E], es ...E) bool

ContainsNoneBy returns true if the stream contains none of the given elements; false otherwise. The elements are compared using the given cmp.Comparer.

Example usage:

out := stream.ContainsNoneBy(stream.Of(1, 2, 3), cmp.Natural[int](), 4, 5) // true
out = stream.ContainsNoneBy(stream.Of(1, 2, 3), cmp.Natural[int](), 2, 4) // false

func Count

func Count[E any](s Stream[E]) (count int64)

Count returns the number of elements in the stream. The stream is fully consumed.

Example usage:

n := stream.Count(stream.Of(1, 2, 3)) // 3

func DebugString

func DebugString[E any](s Stream[E]) string

DebugString returns a string representation of up to the first 100 elements in the stream. The string is formatted like `<e1, e2, e3>` where e1, e2, e3 are the string representations of the elements. If the stream has more than 100 elements, the string will end with `...>` to indicate that the stream was truncated. Useful for debugging.

func ExactlySame added in v1.1.7

func ExactlySame[E comparable](s1, s2 Stream[E]) bool

ExactlySame returns true if the two streams are exactly the same; false otherwise. The element type E must be comparable.

Example usage:

out := stream.ExactlySame(stream.Of(1, 2, 3), stream.Of(1, 2, 3)) // true
out = stream.ExactlySame(stream.Of(1, 2, 3), stream.Of(1, 2, 4)) // false

func ExactlySameBy added in v1.1.7

func ExactlySameBy[E any](s1, s2 Stream[E], compare cmp.Comparer[E]) bool

ExactlySameBy returns true if the two streams are exactly the same; false otherwise. The elements are compared using the given cmp.Comparer.

Example usage:

out := stream.ExactlySameBy(stream.Of(1, 2, 3), stream.Of(1, 2, 3), cmp.Natural[int]()) // true
out = stream.ExactlySameBy(stream.Of(1, 2, 3), stream.Of(1, 2, 4), cmp.Natural[int]()) // false

func First

func First[E any](s Stream[E]) (first opt.Optional[E])

First returns the first element in the stream; an empty opt.Optional, if the stream is empty.

Example usage:

out := stream.First(stream.Of(1, 2, 3)) // Some(1)
out = stream.First(stream.Empty[int]()) // None()

func ForEach

func ForEach[E any](s Stream[E], yield func(E))

ForEach invokes the given consumer for each element in the stream.

Example usage:

stream.ForEach(stream.Of(1, 2, 3), func(e int) bool {
    fmt.Println(e)
})

Output:

1
2
3

func IndexOfFirstMatch added in v1.1.7

func IndexOfFirstMatch[E any](s Stream[E], p Predicate[E]) opt.Optional[int64]

IndexOfFirstMatch returns the index of the first element that passes the given Predicate. If no element passes the Predicate, an empty Optional is returned.

Example usage:

out := stream.IndexOfFirstMatch(stream.Of(1, 2, 3, 4), pred.GreaterThan(2)) // opt.Of(2)
out = stream.IndexOfFirstMatch(stream.Of(1, 2, 3), pred.GreaterThan(3)) // opt.Empty[int64]()

func IndexOfLastMatch added in v1.1.7

func IndexOfLastMatch[E any](s Stream[E], p Predicate[E]) opt.Optional[int64]

IndexOfLastMatch returns the index of the last element that passes the given Predicate. If no element passes the Predicate, an empty Optional is returned.

Example usage:

out := stream.IndexOfLastMatch(stream.Of(1, 2, 3, 4), pred.GreaterThan(2)) // opt.Of(4)
out = stream.IndexOfLastMatch(stream.Of(1, 2, 3), pred.GreaterThan(3)) // opt.Empty[int64]()

func IsEmpty

func IsEmpty[E any](s Stream[E]) (empty bool)

IsEmpty returns true if the stream is empty; otherwise false.

Example usage:

empty := stream.IsEmpty(stream.Of(1, 2, 3)) // false
empty := stream.IsEmpty(stream.Empty[int]()) // true

func Last

func Last[E any](s Stream[E]) (last opt.Optional[E])

Last returns the last element in the stream; an empty opt.Optional, if the stream is empty.

Example usage:

out := stream.Last(stream.Of(1, 2, 3)) // Some(3)
out = stream.Last(stream.Empty[int]()) // None()

func Max

func Max[E constraint.Ordered](s Stream[E]) (max opt.Optional[E])

Max returns the maximum element in the stream. Uses the natural ordering of type E to compare elements. If the stream is empty, then an empty opt.Optional is returned.

Example usage:

max := stream.Max(stream.Of(3, 1, 2)) // Some(3)
max = stream.Max(stream.Empty[int]()) // None()

func MaxBy

func MaxBy[E any](s Stream[E], compare cmp.Comparer[E]) (max opt.Optional[E])

MaxBy returns the maximum element in the stream, or the zero value of the type parameter E if the stream is empty. Uses the given cmp.Comparer to compare elements. If the stream is empty, then an empty opt.Optional is returned.

Example usage:

max := stream.MaxBy(stream.Of(3, 1, 2), cmp.Natural[int]()) // Some(3)
max = stream.MaxBy(stream.Empty[int](), cmp.Natural[int]()) // None()

func Min

func Min[E constraint.Ordered](s Stream[E]) (min opt.Optional[E])

Min returns the minimum element in the stream, or the zero value of the type parameter E if the stream is empty. If the stream is empty, the 'ok' return value is false; otherwise it is true. Uses the natural ordering of type E to compare elements.

Example usage:

min := stream.Min(stream.Of(3, 1, 2)) // Some(1)
min = stream.Min(stream.Empty[int]()) // None()

func MinBy

func MinBy[E any](s Stream[E], compare cmp.Comparer[E]) (min opt.Optional[E])

MinBy returns the minimum element in the stream. Uses the given cmp.Comparer to compare elements. If the stream is empty, then an empty opt.Optional is returned.

Example usage:

min := stream.MinBy(stream.Of(3, 1, 2), cmp.Natural[int]()) // Some(1)
min = stream.MinBy(stream.Empty[int](), cmp.Natural[int]()) // None()

func NoneMatch

func NoneMatch[E any](s Stream[E], p Predicate[E]) bool

NoneMatch returns true if no elements in the stream match the given Predicate. If the stream is empty, it returns true.

Example usage:

out := stream.NoneMatch(stream.Of(1, 2, 3), pred.GreaterThan(3)) // true
out = stream.NoneMatch(stream.Of(1, 2, 3), pred.GreaterThan(2)) // false

func Reduce

func Reduce[E any](s Stream[E], reduce Reducer[E]) opt.Optional[E]

Reduce combines the elements of the stream into a single value using the given reducer function. If the stream is empty, then an empty opt.Optional is returned. The stream is fully consumed.

Example usage:

out := stream.Reduce(
  stream.Of(1, 2, 3),
  func(a, e int) int { // Reduce values by addition.
    return a + e
  },
) // Some(6)

out = stream.Reduce(
  stream.Empty[int](),
  func(a, e int) int { // Reduce values by addition.
    return a + e
  },
) // None()

func SetEqual added in v1.1.6

func SetEqual[E comparable](s1, s2 Stream[E]) bool

SetEqual returns true if the two streams contain the same elements, ignoring order and duplicates (ie: set equality). The element type E must be comparable.

Example usage:

ok := stream.SetEqual(stream.Of(1, 2, 3), stream.Of(3, 2, 1))
fmt.Println(ok) // "true"

func SetEqualBy added in v1.1.6

func SetEqualBy[E any](s1, s2 Stream[E], compare cmp.Comparer[E]) bool

SetEqualBy returns true if the two streams contain the same elements (in any order), compared by the given cmp.Comparer.

Example usage:

ok := stream.SetEqualBy(stream.Of(1, 2, 3), stream.Of(3, 2, 1), cmp.Natural[int]())
fmt.Println(ok) // "true"

func StringJoin

func StringJoin(s Stream[string], sep string) string

StringJoin concatenates the elements of the provided stream of strings into a single string, using the specified separator.

Example usage:

s := stream.Of("foo", "bar", "baz")
out := stream.StringJoin(s, ", ") // "foo, bar, baz"

func Subset added in v1.1.6

func Subset[E comparable](s1, s2 Stream[E]) bool

Subset returns true if all elements of the first stream are in the second stream. The element type E must be comparable.

Example usage:

ok := stream.Subset(stream.Of(1, 2), stream.Of(1, 2, 3, 4))
fmt.Println(ok) // "true"

func SubsetBy added in v1.1.6

func SubsetBy[E any](s1, s2 Stream[E], compare cmp.Comparer[E]) bool

SubsetBy returns true if all elements of the first stream are in the second stream, compared by the given cmp.Comparer.

Example usage:

ok := stream.SubsetBy(stream.Of(1, 2), stream.Of(1, 2, 3, 4), cmp.Natural[int]())
fmt.Println(ok) // "true"

func Sum

func Sum[R, E constraint.RealNumber](s Stream[E]) R

Sum computes the sum of all elements in the stream of any real-number type E and returns the result as real-number type F. The result of an empty stream is the zero value of type F. The stream is fully consumed.

Example usage:

n1 := stream.Sum[int](stream.Of(1, 2, 3)) // 6 (int)
n2 := stream.Sum[float64](stream.Of(1, 2, 3)) // 6.0 (float64)

func SumComplex

func SumComplex[R, E constraint.Complex](s Stream[E]) R

SumComplex computes the sum of all elements in the stream of any complex-number type E and returns the result as complex-number type F. The result of an empty stream is the zero value of type F. The stream is fully consumed.

Example usage:

n := stream.SumComplex[complex128](stream.Of(1+i, 2+i, 3+i)) // 6+3i (complex128)

func Superset added in v1.1.6

func Superset[E comparable](s1, s2 Stream[E]) bool

Superset returns true if all elements of the second stream are in the first stream. The element type E must be comparable.

Example usage:

ok := stream.Superset(stream.Of(1, 2, 3, 4), stream.Of(1, 2))
fmt.Println(ok) // "true"

func SupersetBy added in v1.1.6

func SupersetBy[E any](s1, s2 Stream[E], compare cmp.Comparer[E]) bool

SupersetBy returns true if all elements of the second stream are in the first stream, compared by the given cmp.Comparer.

Example usage:

ok := stream.SupersetBy(stream.Of(1, 2, 3, 4), stream.Of(1, 2), cmp.Natural[int]())
fmt.Println(ok) // "true"

func ToRangeBiFunc

func ToRangeBiFunc[K, V any](s Stream[pair.Pair[K, V]]) func(func(K, V) bool) bool

ToRangeBiFunc converts the given Stream of `pair.Pair` with types K and V into a range bi-function with the same parameter types. This exists for compatibility with the range-over-func support in Go (1.22+).

func ToRangeFunc

func ToRangeFunc[E any](s Stream[E]) func(func(E) bool) bool

ToRangeFunc converts the given Stream of type E into a range function of the same parameter type. This exists for compatibility with the range-over-func support in Go (1.22+).

Types

type Accumulator

type Accumulator[A, E any] func(a A, e E) (result A)

Accumulator represents a function that takes an accumulated value of type A and an element of type E, and returns the updated accumulated value of type A. The Accumulator is commonly used in the `Aggregate` function to combine elements of a stream into a single result.

type Combiner

type Combiner[E1, E2, F any] func(E1, E2) F

Combiner represents a function that combines two elements of type E1 and E2 into an element of type F. It is used in the Combine operation.

type Consumer

type Consumer[E any] func(yield E) (cont bool)

Consumer represents a function that accepts a yielded element of type E and returns a boolean value. The boolean value indicates whether the consumer wishes to continue accepting elements. If the consumer returns false, the caller must stop yielding elements.

type Finisher

type Finisher[A, F any] func(a A) (result F)

Finisher represents a function that takes an accumulated value of type A and returns the finished result of type F. The Finisher is commonly used in the `Aggregate` function to compute the final result after all elements have been accumulated.

type Generator

type Generator[E any] func() E

Generator represents a function that produces an infinite sequence of elements of type E. Used by the Generate function.

type Mapper

type Mapper[E, F any] func(from E) (to F)

Mapper represents a function that transforms an input of type E to an output of type F. It is used in the Map operation. It must be idempotent, free of side effects, and thread-safe.

type OptionalCombiner

type OptionalCombiner[E1, E2, F any] func(E1, E2) opt.Optional[F]

OptionalCombiner represents a function that combines two elements of type E1 and E2 into an opt element of type F. If the elements cannot be combined, the function must return an empty opt. It is used in the CombineOrDiscard operation.

type OptionalMapper

type OptionalMapper[E, F any] func(from E) opt.Optional[F]

OptionalMapper represents a function that transforms an input of type E to an opt output of type F. If the input cannot be transformed, the function must return an empty opt. It is used in the MapOrDiscard operation. It must be idempotent, free of side effects, and thread-safe.

type Predicate

type Predicate[E any] func(e E) (pass bool)

Predicate is a function that accepts a value of type E and returns a boolean. It is used to test values for a given property. It must be idempotent, free of side effects, and thread-safe.

type Reducer

type Reducer[E any] func(e1, e2 E) (result E)

Reducer represents a function that takes two inputs of type E and returns an output of type E. The Reducer is commonly used in the `Reduce` function to combine elements of a stream into a single result.

type SliceMapper added in v1.1.1

type SliceMapper[E, F any] func(from E) (to []F)

SliceMapper represents a function that takes an input of type E and returns an output slice of type F. The SliceMapper function is typically used as a parameter of the FlatMapSlice function. It must be idempotent, free of side effects, and thread-safe.

type Stream

type Stream[E any] func(c Consumer[E]) bool

Stream represents a function that produces a sequence of elements of type E and sends them to the given Consumer.

Streams are lazy, meaning they only produce elements when the consumer is invoked. Furthermore, streams are idempotent, meaning they can be invoked multiple times with the same result. However, the order of the elements is not guaranteed to be the same across multiple invocations.

If the Consumer returns false, the stream must stop producing elements and return false immediately. If the stream is exhausted, it must return true.

func AggregateByKey

func AggregateByKey[K comparable, V, A, F any](s Stream[pair.Pair[K, V]], identity A, accumulate Accumulator[A, V], finish Finisher[A, F]) Stream[pair.Pair[K, F]]

AggregateByKey returns a stream that aggregates key-value pairs by key. The resulting stream contains key-value pairs where the key is the same, and the value is the result of aggregating all the values that had that key. This is a generalization of ReduceByKey that allows an intermediate accumulated value to be of a different type than both the input and the final result. The accumulated value is initialized with the given identity value, and then each element from the input stream is combined with the accumulated value using the given `accumulate` function. Once all elements have been accumulated, the accumulated value is transformed into the final result using the given `finish` function. The order of the elements is not guaranteed.

Example usage:

s := stream.AggregateByKey(
  stream.Of(
    pair.Of("foo", 1),
    pair.Of("bar", 2),
    pair.Of("foo", 3),
  ),
  0, // Initial value
  func(a int, b int) int { // Accumulate values with addition
    return a + b
  },
  func(a int) string { // Finish values with string conversion
    return fmt.Sprintf("%d", a)
  },
)
out := stream.DebugString(s) // "<("foo", "4"), ("bar", "2")>"

func AggregateBySortedKey

func AggregateBySortedKey[K any, V, A, F any](s Stream[pair.Pair[K, V]], keyCompare cmp.Comparer[K], identity A, accumulate Accumulator[A, V], finish Finisher[A, F]) Stream[pair.Pair[K, F]]

AggregateBySortedKey returns a stream that aggregates key-value pairs by key using the given cmp.Comparer to compare keys. The resulting stream contains key-value pairs where the key is the same, and the value is the result of aggregating all the values that had that key. This is a generalization of ReduceBySortedKey that allows an intermediate accumulated value to be of a different type than both the input and the final result. The accumulated value is initialized with the given identity value, and then each element from the input stream is combined with the accumulated value using the given `accumulate` function. Once all elements have been accumulated, the accumulated value is transformed into the final result using the given `finish` function. The order of the elements is determined by the given cmp.Comparer.

Example usage:

s := stream.AggregateBySortedKey(
  stream.Of(
    pair.Of("foo", 1),
    pair.Of("bar", 2),
    pair.Of("foo", 3),
  ),
  cmp.Natural[string](), // Compare keys naturally
  0, // Initial value
  func(a int, b int) int { // Accumulate values with addition
    return a + b
  },
  func(a int) string { // Finish values with string conversion
    return fmt.Sprintf("%d", a)
  },
)
out := stream.DebugString(s) // "<("bar", "2"), ("foo", "4")>"

func Cache

func Cache[E any](s Stream[E]) Stream[E]

Cache returns a stream that caches all elements from the given stream. The first call to the returned stream will cache all elements from the given stream (and exhaust it). Subsequent calls to the returned stream will replay the cache.

func Combine

func Combine[E1, E2, F any](s1 Stream[E1], s2 Stream[E2], combine Combiner[E1, E2, F]) Stream[F]

Combine combines the elements of two streams into a single stream using the given Combiner function. The resulting stream will have the same number of elements as the shorter of the two input streams.

Example usage:

s := stream.Combine(
  stream.Of(1, 2, 3),
  stream.Of("foo", "bar"),
  func(i int, s string) string {
    return fmt.Sprintf("%s%d", s, i)
  },
)
out := stream.DebugString(s) // "<foo1, bar2>"

func CombineOrDiscard

func CombineOrDiscard[E1, E2, F any](s1 Stream[E1], s2 Stream[E2], combine OptionalCombiner[E1, E2, F]) Stream[F]

CombineOrDiscard combines the elements of two streams into a single stream using the given OptionalCombiner function or discards them, if the combiner returns an empty opt. The resulting stream will have at most the same number of elements as the shorter of the two input streams.

Example usage:

s := stream.CombineOrDiscard(
  stream.Of(1, 2, 3),
  stream.Of("foo", "bar"),
  func(i int, s string) opt.Optional[string] {
    if i == 2 {
      return opt.Empty[string]()
    }
    return opt.Of(fmt.Sprintf("%s%d", s, i))
  },
)
out := stream.DebugString(s) // "<foo1>"

func CountByKey

func CountByKey[K comparable, V any](s Stream[pair.Pair[K, V]]) Stream[pair.Pair[K, int64]]

CountByKey returns a stream that counts the number of elements for each key. The resulting stream contains key-value pairs where the key is the same, and the value is the number of elements that had that key. The order of the elements is not guaranteed.

Example usage:

s := stream.CountByKey(
  stream.Of(
    pair.Of("foo", 1),
    pair.Of("bar", 2),
    pair.Of("foo", 3),
  ),
)
out := stream.DebugString(s) // "<("foo", 2), ("bar", 1)>"

func CountBySortedKey

func CountBySortedKey[K any, V any](s Stream[pair.Pair[K, V]], keyCompare cmp.Comparer[K]) Stream[pair.Pair[K, int64]]

CountBySortedKey returns a stream that counts the number of elements for each key using the given cmp.Comparer to compare keys. The resulting stream contains key-value pairs where the key is the same, and the value is the number of elements that had that key. The order of the elements is determined by the given cmp.Comparer.

Example usage:

s := stream.CountBySortedKey(
  stream.Of(
    pair.Of("foo", 1),
    pair.Of("bar", 2),
    pair.Of("foo", 3),
  ),
  cmp.Natural[string](), // Compare keys naturally
)
out := stream.DebugString(s) // "<("bar", 1), ("foo", 2)>"

func CountBySortedValue added in v1.1.4

func CountBySortedValue[V any](s Stream[V], valueCompare cmp.Comparer[V]) Stream[pair.Pair[V, int64]]

CountBySortedValue returns a stream that counts the number of elements for each value using the given cmp.Comparer to compare values. The resulting stream contains key-value pairs where the key is the same, and the value is the number of elements that had that value. The order of the elements is determined by the given cmp.Comparer.

Example usage:

s := stream.CountBySortedValue(
  stream.Of(1, 2, 3, 1, 2),
  cmp.Natural[int](), // Compare values naturally
)
out := stream.DebugString(s) // "<(1, 2), (2, 2), (3, 1)>"

func CountByValue added in v1.1.4

func CountByValue[V comparable](s Stream[V]) Stream[pair.Pair[V, int64]]

CountByValue returns a stream that counts the number of elements for each value. The resulting stream contains key-value pairs where the key is the same, and the value is the number of elements that had that value. The order of the elements is not guaranteed.

Example usage:

s := stream.CountByValue(
  stream.Of(1, 2, 3, 1, 2),
)
out := stream.DebugString(s) // "<(1, 2), (2, 2), (3, 1)>"

func Difference

func Difference[E comparable](s1, s2 Stream[E]) Stream[E]

Difference returns a stream that contains elements that are in the first stream but not in the second stream. The element type E must be comparable. The order of the elements is not guaranteed.

Example usage:

s := stream.Difference(stream.Of(1, 2, 3, 4, 5), stream.Of(4, 5, 6))
out := stream.DebugString(s) // "<1, 2, 3>"

func DifferenceBy

func DifferenceBy[E any](s1, s2 Stream[E], compare cmp.Comparer[E]) Stream[E]

DifferenceBy returns a stream that contains elements that are in the first stream but not in the second stream, compared by the given cmp.Comparer. The order of the elements is determined by the comparer.

Example usage:

s := stream.DifferenceBy(stream.Of(1, 2, 3, 4, 5), stream.Of(4, 5, 6), cmp.Natural[int]())
out := stream.DebugString(s) // "<1, 2, 3>"

func Distinct

func Distinct[E comparable](s Stream[E]) Stream[E]

Distinct returns a stream that only contains distinct elements of some comparable type E.

Example usage:

s := stream.Distinct(stream.Of(1, 2, 2, 3))
out := stream.DebugString(s) // "<1, 2, 3>"

func DistinctBy

func DistinctBy[E any](s Stream[E], compare cmp.Comparer[E]) Stream[E]

DistinctBy returns a stream that only contains distinct elements using the given comparer to compare elements.

Example usage:

s := stream.DistinctBy(stream.Of(1, 2, 2, 3), cmp.Natural[int]())
out := stream.DebugString(s) // "<1, 2, 3>"

func Empty

func Empty[E any]() Stream[E]

Empty returns a stream that does not contain any elements. It always returns true when invoked with a consumer.

Example usage:

s := stream.Empty[int]()
out := stream.DebugString(s) // "<>"

func Filter

func Filter[E any](s Stream[E], p Predicate[E]) Stream[E]

Filter returns a stream that only contains elements that pass the given Predicate.

Example usage:

s := stream.Filter(stream.Of(1, 2, 3), func(e int) bool {
  return e % 2 == 0
})
out := stream.DebugString(s) // "<2>"

func FilterIndexed added in v1.1.7

func FilterIndexed[E any](s Stream[E], p func(E) bool) Stream[pair.Pair[int64, E]]

FilterIndexed returns a stream that only contains elements and their index that pass the given Predicate.

Example usage:

s := stream.FilterIndexed(stream.Of(1, 2, 3, 4), func(e int) bool {
  return e % 2 == 0
})
out := stream.DebugString(s) // "<(1, 2), (3, 4)>"

func FlatMap

func FlatMap[E, F any](s Stream[E], m StreamMapper[E, F]) Stream[F]

FlatMap applies a StreamMapper function to each element from the given stream and flattens the returned streams into an output stream.

Example usage:

s := stream.FlatMap(
  stream.Of(1, 2, 3),
  func(e int) stream.Stream[string] { // e -> <"e", "e">
    return stream.Of(mapper.Sprint(e), mapper.Sprint(e))
  },
)
out := stream.DebugString(s) // "<1, 1, 2, 2, 3, 3>"

func FlatMapSlice added in v1.1.1

func FlatMapSlice[E, F any](s Stream[E], m SliceMapper[E, F]) Stream[F]

FlatMapSlice applies a SliceMapper function to each element from the given stream and flattens the returned slices into an output stream.

Example usage:

s := stream.FlatMapSlice(
  stream.Of(1, 2, 3),
  func(e int) []string { // e -> ["e", "e"]
    return []string{mapper.Sprint(e), mapper.Sprint(e)}
  },
)
out := stream.DebugString(s) // "<1, 1, 2, 2, 3, 3>"

func FromChannel

func FromChannel[E any](ch <-chan E) Stream[E]

FromChannel returns a stream that reads elements from the given channel until it is closed.

Note: If the channel is not closed, the stream will block forever.
Note: If the consumer returns false, channel writes may block forever if the channel is unbuffered.

Example usage:

ch := make(chan int)
go func() {
  ch <- 1
  ch <- 2
  close(ch)
}()
s := stream.FromChannel(ch)
out := stream.DebugString(s) // "<1, 2>"

func FromChannelCtx

func FromChannelCtx[E any](ctx context.Context, ch <-chan E) Stream[E]

FromChannelCtx behaves like FromChannel, but it returns immediately when the context is done.

Note: If the context is done, channel writes may block forever if the channel is unbuffered.

Example usage:

ch := make(chan int)
go func() {
  ch <- 1
  ch <- 2
  close(ch)
}()
s := stream.FromChannelCtx(ctx, ch)
out := stream.DebugString(s) // "<1, 2>"

func FromMap

func FromMap[K comparable, V any](m map[K]V) Stream[pair.Pair[K, V]]

FromMap returns a stream that iterates over the key-value pairs in the given map. The key-value pairs are encapsulated in `pair.Pair` objects. The order of the key-value pairs is not guaranteed.

Example usage:

s := stream.FromMap(map[int]string{1: "foo", 2: "bar"})
out := stream.DebugString(s) // "<(1, foo), (2, bar)>"

func FromMapKeys

func FromMapKeys[K comparable, V any](m map[K]V) Stream[K]

FromMapKeys takes a map and returns a stream of its keys. The order of the keys is not guaranteed.

Example usage:

s := stream.FromMapKeys(map[int]string{1: "foo", 2: "bar"})
out := stream.DebugString(s) // "<1, 2>" // Order not guaranteed.

func FromMapValues

func FromMapValues[K comparable, V any](m map[K]V) Stream[V]

FromMapValues takes a map and returns a stream of its values. The order of the values is not guaranteed.

Example usage:

s := stream.FromMapValues(map[int]string{1: "foo", 2: "bar"})
out := stream.DebugString(s) // "<foo, bar>" // Order not guaranteed.

func FromRangeBiFunc

func FromRangeBiFunc[K, V any](f func(func(K, V) bool) bool) Stream[pair.Pair[K, V]]

FromRangeBiFunc converts a range bi-function of parameter types K and V into a Stream of `pair.Pair` with the same types. This exists for compatibility with the range-over-func support in Go (1.22+).

func FromRangeFunc

func FromRangeFunc[E any](f func(func(E) bool) bool) Stream[E]

FromRangeFunc adapts a range function of parameter type E to a Stream of the same type. This exists for compatibility with the range-over-func support in Go (1.22+).

func FromSlice

func FromSlice[E any](s []E) Stream[E]

FromSlice creates a stream that iterates over the elements of the given slice. The order of the elements is guaranteed to be the same as the order in the slice.

Example usage:

s := stream.FromSlice([]int{1, 2, 3})
out := stream.DebugString(s) // "<1, 2, 3>"

func FromSliceBackwards

func FromSliceBackwards[E any](s []E) Stream[E]

FromSliceBackwards creates a stream that iterates over the elements of the given slice in reverse order. The order of the elements is guaranteed to be the same as the order in the slice (but backwards).

Example usage:

s := stream.FromSliceBackwards([]int{1, 2, 3})
out := stream.DebugString(s) // "<3, 2, 1>"

func FromSliceWithIndex

func FromSliceWithIndex[E any](s []E) Stream[pair.Pair[int, E]]

FromSliceWithIndex returns a stream that iterates over the elements of the input slice along with their indices. The stream returns a `pair.Pair` with both the index and the value of each element. The order of the elements is guaranteed to be the same as the order in the slice.

Example usage:

s := stream.FromSliceWithIndex([]int{1, 2, 3})
out := stream.DebugString(s) // "<(0, 1), (1, 2), (2, 3)>"

func FromSliceWithIndexBackwards

func FromSliceWithIndexBackwards[E any](s []E) Stream[pair.Pair[int, E]]

FromSliceWithIndexBackwards returns a stream that iterates over the elements of the input slice along with their indices in reverse order. The stream returns a `pair.Pair` with both the index and the value of each element. The order of the elements is guaranteed to be the same as the order in the slice (but backwards).

Example usage:

s := stream.FromSliceWithIndexBackwards([]int{1, 2, 3})
out := stream.DebugString(s) // "<(2, 3), (1, 2), (0, 1)>"

func Generate

func Generate[E any](next Generator[E]) Stream[E]

Generate returns an infinite stream that produces elements by invoking the given generator function.

Example usage:

s := stream.Generate(func() int { return 1	})
out := stream.DebugString(s) // "<1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...>"

func GroupByKey

func GroupByKey[K comparable, V any](s Stream[pair.Pair[K, V]]) Stream[pair.Pair[K, []V]]

GroupByKey returns a stream that values key-value pairs by key. The resulting stream contains key-value pairs where the key is the same, and the value is a slice of all the values that had that key. The key type K must be comparable. The order of the key-value pairs is not guaranteed.

Example usage:

s := stream.GroupByKey(
  stream.Of(
    pair.Of("foo", 1),
    pair.Of("bar", 2),
    pair.Of("foo", 3),
  ),
)
out := stream.DebugString(s) // "<(foo, [1, 3]), (bar, [2])>"

func GroupBySortedKey

func GroupBySortedKey[K any, V any](s Stream[pair.Pair[K, V]], keyCompare cmp.Comparer[K]) Stream[pair.Pair[K, []V]]

GroupBySortedKey returns a stream that values key-value pairs by key using the given cmp.Comparer to compare keys. The resulting stream contains key-value pairs where the key is the same, and the value is a slice of all the values that had that key. The order of the key-value pairs is determined by the given cmp.Comparer.

Example usage:

s := stream.GroupBySortedKey(
  stream.Of(
    pair.Of("foo", 1),
    pair.Of("bar", 2),
    pair.Of("foo", 3),
  ),
  cmp.Natural[string](), // Compare keys naturally
)
out := stream.DebugString(s) // "<(bar, [2]), (foo, [1, 3])>"

func IndexOfMatches added in v1.1.7

func IndexOfMatches[E any](s Stream[E], p Predicate[E]) Stream[int64]

IndexOfMatches returns a stream of indices of elements that pass the given Predicate.

Example usage:

out := stream.IndexOfMatches(stream.Of(1, 2, 3), pred.GreaterThan(2)) // "<2>"
out = stream.IndexOfMatches(stream.Of(1, 2, 3), pred.GreaterThan(3)) // "<>"

func Intersection

func Intersection[E comparable](s1, s2 Stream[E]) Stream[E]

Intersection returns a stream that contains elements that are in the given streams. The element type E must be comparable. The order of the elements is not guaranteed.

Example usage:

s := stream.Intersection(stream.Of(1, 2, 3, 4, 5), stream.Of(4, 5, 6))
out := stream.DebugString(s) // "<4, 5>"

func IntersectionAll

func IntersectionAll[E comparable](ss ...Stream[E]) Stream[E]

IntersectionAll returns a stream that contains elements that are in all the given streams. The element type E must be comparable. The order of the elements is not guaranteed.

Example usage:

s := stream.IntersectionAll(stream.Of(1, 2, 3, 4, 5), stream.Of(4, 5, 6), stream.Of(4, 5, 7))
out := stream.DebugString(s) // "<4, 5>"

func IntersectionAllBy

func IntersectionAllBy[E any](compare cmp.Comparer[E], ss ...Stream[E]) Stream[E]

IntersectionAllBy returns a stream that contains elements that are in all the given streams, compared by the given cmp.Comparer. The order of the elements is determined by the comparer.

Example usage:

s := stream.IntersectionAllBy(cmp.Natural[int](), stream.Of(1, 2, 3, 4, 5), stream.Of(4, 5, 6), stream.Of(4, 5, 7))
out := stream.DebugString(s) // "<4, 5>"

func IntersectionBy

func IntersectionBy[E any](s1, s2 Stream[E], compare cmp.Comparer[E]) Stream[E]

IntersectionBy returns a stream that contains elements that are in the given streams, compared by the given cmp.Comparer. The order of the elements is determined by the comparer.

Example usage:

s := stream.IntersectionBy(stream.Of(1, 2, 3, 4, 5), stream.Of(4, 5, 6), cmp.Natural[int]())
out := stream.DebugString(s) // "<4, 5>"

func Interval

func Interval[N constraint.RealNumber](start, end, step N) Stream[N]

Interval returns a stream of real-number type N from the half-open interval `[start, end)` using the given step size. If the step size is negative, then the stream will be decreasing; otherwise, it will be increasing.

Example usage:

s := stream.Interval(0, 5, 1)
out := stream.DebugString(s) // "<0, 1, 2, 3, 4>"
s := stream.Interval(0, 5, 2)
out := stream.DebugString(s) // "<0, 2, 4>"
s = stream.Interval(5, 0, -2)
out = stream.DebugString(s) // "<5, 3, 1>"

func Iterate

func Iterate[E any](next func() (E, bool)) Stream[E]

Iterate returns a stream of elements produced by the given iterator function. When the iterator function returns false, the stream ends.

Example usage:

i := 0
s := stream.Iterate(func() (int, bool) {
  if i < 3 {
    i++
    return i, true
  }
  return 0, false
})
out := stream.DebugString(s) // "<1, 2, 3>"

func IterateOptional

func IterateOptional[E any](next func() opt.Optional[E]) Stream[E]

IterateOptional returns a stream of elements produced by the given iterator function. When the iterator function returns an empty opt.Optional, the stream ends.

Example usage:

i := 0
s := stream.IterateOptional(func() opt.Optional[int] {
  if i < 3 {
    i++
    return opt.Of(i)
  }
  return opt.Empty[int]()
})
out := stream.DebugString(s) // "<1, 2, 3>"

func Limit

func Limit[E any](s Stream[E], n int64) Stream[E]

Limit returns a stream that is limited to the first `n` elements. If the input stream has fewer than `n` elements, the returned stream will have the same number of elements.

Example usage:

s := stream.Limit(stream.Of(1, 2, 3), 2)
out := stream.DebugString(s) // "<1, 2>"

func Map

func Map[E, F any](s Stream[E], m Mapper[E, F]) Stream[F]

Map applies a Mapper function to each element in a stream and returns a new stream containing the mapped elements.

Example usage:

s := stream.Map(stream.Of(1, 2, 3), mapper.Sprint)
out := stream.DebugString(s) // "<1, 2, 3>"

func MapOrDiscard

func MapOrDiscard[E, F any](s Stream[E], m OptionalMapper[E, F]) Stream[F]

MapOrDiscard applies an OptionalMapper function to each element in a stream and returns a new stream containing the mapped elements. If the OptionalMapper returns an empty opt, the element is discarded from the stream.

Example usage:

s := stream.MapOrDiscard(stream.Of("1", "foo", "3"), mapper.TryParseInt[int](10, 64))
out := stream.DebugString(s) // "<1, 3>"

func MaxByKey

func MaxByKey[K comparable, V constraint.Ordered](s Stream[pair.Pair[K, V]]) Stream[pair.Pair[K, V]]

MaxByKey returns a stream that finds the maximum value for each key. The resulting stream contains key-value pairs where the key is the same, and the value is the maximum value that had that key. The key type K must be comparable. The value type V must be ordered. The order of the elements is not guaranteed.

Example usage:

s := stream.MaxByKey(
  stream.Of(
    pair.Of("foo", 1),
    pair.Of("bar", 2),
    pair.Of("foo", 3),
  ),
)
out := stream.DebugString(s) // "<("foo", 3), ("bar", 2)>"

func MaxBySortedKey

func MaxBySortedKey[K any, V constraint.Ordered](s Stream[pair.Pair[K, V]], keyCompare cmp.Comparer[K]) Stream[pair.Pair[K, V]]

MaxBySortedKey returns a stream that finds the maximum value for each key using the given cmp.Comparer to compare keys. The resulting stream contains key-value pairs where the key is the same, and the value is the maximum value that had that key. The value type V must be ordered. The order of the elements is determined by the given cmp.Comparer.

Example usage:

s := stream.MaxBySortedKey(
  stream.Of(
    pair.Of("foo", 1),
    pair.Of("bar", 2),
    pair.Of("foo", 3),
  ),
  cmp.Natural[string](), // Compare keys naturally
)
out := stream.DebugString(s) // "<("bar", 2), ("foo", 3)>"

func MinByKey

func MinByKey[K comparable, V constraint.Ordered](s Stream[pair.Pair[K, V]]) Stream[pair.Pair[K, V]]

MinByKey returns a stream that finds the minimum value for each key. The resulting stream contains key-value pairs where the key is the same, and the value is the minimum value that had that key. The key type K must be comparable. The value type V must be ordered. The order of the elements is not guaranteed.

Example usage:

s := stream.MinByKey(
  stream.Of(
    pair.Of("foo", 1),
    pair.Of("bar", 2),
    pair.Of("foo", 3),
  ),
)
out := stream.DebugString(s) // "<("foo", 1), ("bar", 2)>"

func MinBySortedKey

func MinBySortedKey[K any, V constraint.Ordered](s Stream[pair.Pair[K, V]], keyCompare cmp.Comparer[K]) Stream[pair.Pair[K, V]]

MinBySortedKey returns a stream that finds the minimum value for each key using the given cmp.Comparer to compare keys. The resulting stream contains key-value pairs where the key is the same, and the value is the minimum value that had that key. The value type V must be ordered. The order of the elements is determined by the given cmp.Comparer.

Example usage:

s := stream.MinBySortedKey(
  stream.Of(
    pair.Of("foo", 1),
    pair.Of("bar", 2),
    pair.Of("foo", 3),
  ),
  cmp.Natural[string](), // Compare keys naturally
)
out := stream.DebugString(s) // "<("bar", 2), ("foo", 1)>"

func Of

func Of[E any](e ...E) Stream[E]

Of creates a stream from the given elements.

Example usage:

s := stream.Of(1, 2, 3)
out := stream.DebugString(s) // "<1, 2, 3>"

func PadTail

func PadTail[E any](s Stream[E], pad E, length int) Stream[E]

PadTail returns a stream that pads the tail of the given stream with the given 'pad' value until the stream reaches the given length. If the stream is already longer than the given length, then the stream is returned as-is.

Example usage:

s := stream.Pad(stream.Of(1, 2, 3), 0, 5)
out := stream.DebugString(s) // "<1, 2, 3, 0, 0>"

func Peek

func Peek[E any](s Stream[E], peek func(e E)) Stream[E]

Peek decorates the given stream to invoke the given function for each element passing through it. This is useful for debugging or logging elements as they pass through the stream.

Example usage:

s := stream.Peek(stream.Of(1, 2, 3), func(e int) {
  fmt.Println(e)
})
stream.Count(s) // Force the stream to materialize.

Output:

1
2
3

func RandomBool

func RandomBool(source rand.Source) Stream[bool]

RandomBool returns a stream that produces pseudo-random boolean values using the given rand.Source.

func RandomBytes

func RandomBytes(source rand.Source) Stream[byte]

RandomBytes returns a stream that produces pseudo-random byte values using the given rand.Source.

func RandomExpFloat64

func RandomExpFloat64(source rand.Source) Stream[float64]

RandomExpFloat64 returns a stream that produces exponentially-distributed float64 values in the range [0.0, +math.MaxFloat64] using the given rand.Source. The rate (lambda) parameter is 1.0.

func RandomFloat32

func RandomFloat32(source rand.Source) Stream[float32]

RandomFloat32 returns a stream that produces pseudo-random float32 values in the range [0.0, 1.0) using the given rand.Source.

func RandomFloat64

func RandomFloat64(source rand.Source) Stream[float64]

RandomFloat64 returns a stream that produces pseudo-random float64 values in the range [0.0, 1.0) using the given rand.Source.

func RandomInt

func RandomInt(source rand.Source) Stream[int]

RandomInt returns a stream that produces pseudo-random, non-negative int values using the given rand.Source.

func RandomIntn

func RandomIntn(source rand.Source, n int) Stream[int]

RandomIntn returns a stream that produces pseudo-random int values in the range [0, n) using the given rand.Source.

func RandomNormFloat64

func RandomNormFloat64(source rand.Source) Stream[float64]

RandomNormFloat64 returns a stream that produces normally-distributed float64 values in the range [-math.MaxFloat64, +math.MaxFloat64] using the given rand.Source. The mean is 0.0 and the standard deviation is 1.0.

func RandomUint32

func RandomUint32(source rand.Source) Stream[uint32]

RandomUint32 returns a stream that produces pseudo-random uint32 values using the given rand.Source.

func RandomUint64

func RandomUint64(source rand.Source) Stream[uint64]

RandomUint64 returns a stream that produces pseudo-random uint64 values using the given rand.Source.

func ReduceByKey

func ReduceByKey[K comparable, V any](s Stream[pair.Pair[K, V]], reduce Reducer[V]) Stream[pair.Pair[K, V]]

ReduceByKey returns a stream that reduces key-value pairs by key using the given Reducer to reduce values. The resulting stream contains key-value pairs where the key is the same, and the value is the result of reducing all the values that had that key. The order of the elements is not guaranteed.

Example usage:

s := stream.ReduceByKey(
  stream.Of(
    pair.Of("foo", 1),
    pair.Of("bar", 2),
    pair.Of("foo", 3),
  ),
  func(a, b int) int { // Reduce values with addition
    return a + b
  },
)
out := stream.DebugString(s) // "<("foo", 4), ("bar", 2)>"

func ReduceBySortedKey

func ReduceBySortedKey[K any, V any](s Stream[pair.Pair[K, V]], keyCompare cmp.Comparer[K], reduce Reducer[V]) Stream[pair.Pair[K, V]]

ReduceBySortedKey returns a stream that reduces key-value pairs by key using the given cmp.Comparer to compare keys and the given Reducer to reduce values. The resulting stream contains key-value pairs where the key is the same, and the value is the result of reducing all the values that had that key. The order of the elements is determined by the given cmp.Comparer.

Example usage:

s := stream.ReduceBySortedKey(
  stream.Of(
    pair.Of("foo", 1),
    pair.Of("bar", 2),
    pair.Of("foo", 3),
  ),
  cmp.Natural[string](), // Compare keys naturally
  func(a, b int) int { // Reduce values with addition
    return a + b
  },
)
out := stream.DebugString(s) // "<("bar", 2), ("foo", 4)>"

func Repeat

func Repeat[E any](e E) Stream[E]

Repeat returns an infinite stream that always produces the given element.

Example usage:

s := stream.Repeat(1)
out := stream.DebugString(s) // "<1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...>"

func RepeatN

func RepeatN[E any](e E, n int64) Stream[E]

RepeatN returns a stream that produces the given element n times. If n is less than or equal to zero, the stream will be empty.

Example usage:

s := stream.RepeatN(1, 3)
out := stream.DebugString(s) // "<1, 1, 1>"

func Skip

func Skip[E any](s Stream[E], n int64) Stream[E]

Skip returns a stream that skips the first `n` elements. If the input stream has fewer than `n` elements, the returned stream will be empty.

Example usage:

s := stream.Skip(stream.Of(1, 2, 3), 2)
out := stream.DebugString(s) // "<3>"

func Slice added in v1.1.7

func Slice[E any](s Stream[E], start, end int64) Stream[E]

Slice returns a stream that contains elements from the start index (inclusive) to the end index (exclusive). If the start index is greater than the end index, the returned stream will be empty. If the end index is greater than the number of elements in the input stream, the returned stream will contain all elements from the start index.

Example usage:

s := stream.Slice(stream.Of(1, 2, 3), 1, 2)
out := stream.DebugString(s) // "<2>"

func SortAsc

func SortAsc[E constraint.Ordered](s Stream[E]) Stream[E]

SortAsc returns a stream that sorts the elements in ascending order. The elements must implement the Ordered interface.

Example usage:

s := stream.SortAsc(stream.Of(3, 1, 2))
out := stream.DebugString(s) // "<1, 2, 3>"

func SortBy

func SortBy[E any](s Stream[E], compare cmp.Comparer[E]) Stream[E]

SortBy returns a stream that sorts the elements using the given cmp.Comparer.

Example usage:

s := stream.SortBy(stream.Of(3, 1, 2), cmp.Natural[int]())
out := stream.DebugString(s) // "<1, 2, 3>"

func SortDesc

func SortDesc[E constraint.Ordered](s Stream[E]) Stream[E]

SortDesc returns a stream that sorts the elements in descending order. The elements must implement the Ordered interface.

Example usage:

s := stream.SortDesc(stream.Of(3, 1, 2))
out := stream.DebugString(s) // "<3, 2, 1>"

func SumByKey

func SumByKey[K comparable, V constraint.Numeric](s Stream[pair.Pair[K, V]]) Stream[pair.Pair[K, V]]

SumByKey returns a stream that sums the values for each key. The resulting stream contains key-value pairs where the key is the same, and the value is the sum of all the values that had that key. The key type K must be comparable. The value type V must be numeric. The order of the elements is not guaranteed.

Example usage:

s := stream.SumByKey(
  stream.Of(
    pair.Of("foo", 1),
    pair.Of("bar", 2),
    pair.Of("foo", 3),
  ),
)
out := stream.DebugString(s) // "<("foo", 4), ("bar", 2)>"

func SumBySortedKey

func SumBySortedKey[K any, V constraint.Numeric](s Stream[pair.Pair[K, V]], keyCompare cmp.Comparer[K]) Stream[pair.Pair[K, V]]

SumBySortedKey returns a stream that sums the values for each key using the given cmp.Comparer to compare keys. The resulting stream contains key-value pairs where the key is the same, and the value is the sum of all the values that had that key. The value type V must be numeric. The order of the elements is determined by the given cmp.Comparer.

Example usage:

s := stream.SumBySortedKey(
  stream.Of(
    pair.Of("foo", 1),
    pair.Of("bar", 2),
    pair.Of("foo", 3),
  ),
  cmp.Natural[string](), // Compare keys naturally
)
out := stream.DebugString(s) // "<("bar", 2), ("foo", 4)>"

func SymmetricDifference added in v1.1.6

func SymmetricDifference[E comparable](s1, s2 Stream[E]) Stream[E]

SymmetricDifference returns a stream that contains elements that are in either of the given streams, but not in both. The element type E must be comparable. The order of the elements is not guaranteed.

Example usage:

s := stream.SymmetricDifference(stream.Of(1, 2, 3, 4, 5), stream.Of(4, 5, 6))
out := stream.DebugString(s) // "<1, 2, 3, 6>"

func SymmetricDifferenceBy added in v1.1.6

func SymmetricDifferenceBy[E any](s1, s2 Stream[E], compare cmp.Comparer[E]) Stream[E]

SymmetricDifferenceBy returns a stream that contains elements that are in either of the given streams, but not in both, compared by the given cmp.Comparer. The order of the elements is not guaranteed.

Example usage:

s := stream.SymmetricDifferenceBy(stream.Of(1, 2, 3, 4, 5), stream.Of(4, 5, 6), cmp.Natural[int]())
out := stream.DebugString(s) // "<1, 2, 3, 6>"

func Truncate

func Truncate[E any](s Stream[E], length int, tail E) Stream[E]

Truncate returns a stream that limits the given stream to the desired length and appends the given 'tail' value, if the stream is longer than the desired length. The tail value is appended only once, even if the stream is longer than the desired. If the stream is already shorter than the desired length, then the stream is returned as-is.

Example usage:

s := stream.Truncate(stream.Of("a", "b", "c""), 2, "...")
out := stream.DebugString(s) // "<a, b, ...>"

s = stream.Truncate(stream.Of("a", "b", "c""), 3, "...")
out = stream.DebugString(s) // "<a, b, c>"

func Union

func Union[E any](ss ...Stream[E]) Stream[E]

Union combines multiple streams into a single stream (concatenation). The length of the resulting stream is the sum of the lengths of the input streams. If any of the input streams return false when invoked with the consumer, the concatenation stops.

Example usage:

s := stream.Union(stream.Of(1, 2, 3, 4), stream.Of(4, 5, 6))
out := stream.DebugString(s) // "<1, 2, 3, 4, 4, 5, 6>"

func UnzipFirst added in v1.1.5

func UnzipFirst[E, F any](s Stream[pair.Pair[E, F]]) Stream[E]

UnzipFirst returns a stream that contains the first elements of each pair in the input stream.

Example usage:

s := stream.UnzipFirst(
  stream.Of(
    pair.Of(1, "foo"),
    pair.Of(2, "bar"),
  ),
)
out := stream.DebugString(s) // "<1, 2>"

func UnzipSecond added in v1.1.5

func UnzipSecond[E, F any](s Stream[pair.Pair[E, F]]) Stream[F]

UnzipSecond returns a stream that contains the second elements of each pair in the input stream.

Example usage:

s := stream.UnzipSecond(
  stream.Of(
    pair.Of(1, "foo"),
    pair.Of(2, "bar"),
  ),
)
out := stream.DebugString(s) // "<foo, bar>"

func Walk

func Walk[E any](start E, cond Predicate[E], advance Mapper[E, E]) Stream[E]

Walk returns a stream that walks elements beginning at `start`, advanced by the `advance` function, and ending when `cond` predicate returns false.

Example usage:

s := stream.Walk(1, pred.LessThanOrEqual(5), mapper.Increment(2))
out := stream.DebugString(s) // "<1, 3, 5>"

func Zip

func Zip[E, F any](s1 Stream[E], s2 Stream[F]) Stream[pair.Pair[E, F]]

Zip returns a stream that pairs each element in the first stream with the corresponding element in the second stream. The resulting stream will have the same number of elements as the shorter of the two input streams.

Example usage:

s := stream.Zip(stream.Of(1, 2, 3), stream.Of("foo", "bar"))
out := stream.DebugString(s) // "<(1, foo), (2, bar)>"

func ZipWithIndex

func ZipWithIndex[E any, I constraint.Integer](s Stream[E], offset I) Stream[pair.Pair[E, I]]

ZipWithIndex returns a stream that pairs each element in the input stream with its index, starting at the given offset. The index type I must be an integer type.

Example usage:

s := stream.ZipWithIndex(stream.Of("foo", "bar"), 1)
out := stream.DebugString(s) // "<(foo, 1), (bar, 2)>"

type StreamMapper added in v1.1.1

type StreamMapper[E, F any] func(from E) (to Stream[F])

StreamMapper represents a function that takes an input of type E and returns an output stream of type F. The StreamMapper function is typically used as a parameter of the FlatMap function. It must be idempotent, free of side effects, and thread-safe.

Directories

Path Synopsis
Package mapper provides a set of functions for transforming values in Go.
Package mapper provides a set of functions for transforming values in Go.
Package pred provides various generic predicate functions.
Package pred provides various generic predicate functions.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL