gostream

package module
v0.0.0-...-1f6d7dc Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2023 License: BSD-3-Clause Imports: 12 Imported by: 0

README

gostream

gostream package provides a Stream API similar to Java, using the Go2 Generic. This package is an experimental implementation for me to learn the Go Generics.

CAUTION: this package is under construction

Stream interface

Stream interface is a generic interface. As a factory of Stream interface, following functions are available:

  • Of function creates a Stream from a slice.
  • Builder can be used to create a Stream by adding elements.
  • FileLines function returns a Stream of lines of a file.
  • Range function returns a Stream by an incremental step of 1.
  • RangeClosed function returns a Stream by an incremental step of 1.

Stream provides following methods:

  • Filter
  • Sorted
  • Peek
  • Limit
  • Skip
  • ForEach
  • ToSlice
  • Reduce
  • ReduceToOptional
  • Min
  • Max
  • Count
  • AnyMatch
  • AllMatch
  • NoneMatch
  • FindFirst
  • FindAny
  • Parallel

With the Go2 Generic, an interface cannot provided so-called generic method (in Java terms): instead, this package provides top-level functions of which the first parameter is a Stream:

  • Map
  • FlatMap
  • Distinct
  • Sorted
  • Reduce
  • Collect
  • CollectByCollector
  • Empty
  • Iterate
  • IteratN
  • Generate
  • Concat
  • Sum
  • Min
  • Max

For CollectByCollector function, following functions as a Collector are provided:

  • ToSliceCollector
  • ToSetCollector
  • JoiningCollector
  • MappingCollector
  • FlatMappingCollector
  • FilteringCollector
  • GroupingByCollector
  • GroupingByToSliceCollector
  • PartitioningByToSliceCollector
  • PartitioningByCollector
  • ToMapCollector
  • SummarizingCollector
  • SummingCollector
  • CountingCollector
  • ReducingCollector
  • ReducingToOptionalCollector
  • MaxByCollector
  • MinByCollector
  • AveragingInt64Collector
  • AveragingFloat64Collector

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Collect

func Collect[R, T any](
	stream Stream[T],
	supplier function.Supplier[R],
	accumulator function.BiConsumer[R, T],
	combiner function.BiConsumer[R, R],
) R

Collect performs mutable reduction opertion on the elements of stream. A mutable result is one in which reduced value is a mutable result container such as a slice.

func CollectByCollector

func CollectByCollector[T, R, A any](
	stream Stream[T],
	collector *Collector[T, A, R],
) R

CollectByCollector performs mutable reduction operation on the elements of stream using a Collector. A Collector encapsulates the functions used as arguments to Collect(Supplier, BiConsumer, BiConsumer), allowing for resuse of collection strategies and composition of collect operations such as multiple-level grouping or partitioning.

func Identity

func Identity[T any](t T) T

Identity is a function that always returns its input argument

func Reduce

func Reduce[U, T any](
	stream Stream[T],
	identity U,
	accumulator function.BiFunction[U, T, U],
	combiner function.BinaryOperator[U],
) U

Reduce performs a reduction on the elements of stream, using the provided identity, accumulation and combining functions.

func Sum

func Sum[T Number](stream Stream[T]) T

Returns the sum of elements in this stream.

Types

type BaseStream

type BaseStream[T any] interface {
	// Close closes this stream, causing all close handlers for this
	// stream pipeline to be called.
	Close()
}

type Builder

type Builder[T any] struct {
	// contains filtered or unexported fields
}

Builder is a mutable builder for a Stream. This allows the creation of a Stream by generating elements individually and adding them to the Builder.

func (*Builder[T]) Add

func (b *Builder[T]) Add(t T)

Add adds an element to the stream being built.

func (*Builder[T]) Build

func (b *Builder[T]) Build() Stream[T]

Build builds the stream, transitioning this builder to the built state. If there are further attempts to operate on the builder after it has entered the built state, then panic.

type Collector

type Collector[T, A, R any] struct {
	// contains filtered or unexported fields
}

Collector is a mutable reduction operation that accumulates input elements into a mutable result container.

func AveragingFloat64Collector

func AveragingFloat64Collector[T any](
	mapper function.Function[T, float64],
) *Collector[T, *[4]float64, float64]

func AveragingInt64Collector

func AveragingInt64Collector[T any](
	mapper function.Function[T, int64],
) *Collector[T, *[2]int64, float64]

AveragingInt64 returns a Collector that produces the arithmetic mean of an an int64-valued function applied to the input elements. If no elements are present, the result is 0.

func CountingCollector

func CountingCollector[T any]() *Collector[T, *int64, int64]

CountingCollector returns a Collector accepting elements of type T that counts the number of input elements. If no elements are present, the result is 0.

func FilteringCollector

func FilteringCollector[T, A, R any](
	predicate function.Predicate[T],
	downstream *Collector[T, A, R],
) *Collector[T, A, R]

FilteringCollector adapts a Collector to one accepting elements of the same type T by applying the predicate to each input element and only accumulating if the predicate returns true

func FlatMappingCollector

func FlatMappingCollector[T, U, A, R any](
	mapper function.Function[T, Stream[U]],
	downstream *Collector[U, A, R]) *Collector[T, A, R]

FlatMappingCollector adapts Collector accepting elements of type U to one accepting elements of type T by applying a flat mapping function to each input element before accumulation. The flat mapping function maps an input elements to a Stream covering zero or more output elements that are then accumulated downstream.

func GroupingByCollector

func GroupingByCollector[T any, K comparable, A, D any](
	classifier function.Function[T, K],
	downstream *Collector[T, A, D],
) *Collector[T, map[K]A, map[K]D]

GroupingByCollector returns a Collector implementing a cascaded "group by" opertion on input elements of type T, grouping elements according to a classifier function, and then performing a reduction operation on the values associated with a give key using the specified downstream Collector.

func GroupingByToSliceCollector

func GroupingByToSliceCollector[T any, K comparable](
	classifer function.Function[T, K],
) *Collector[T, map[K]*[]T, map[K][]T]

GroupingByToSliceCollector returns a Collector implementing a "group by" operation on input elements of type T, grouping elements according to a classification function, and returning the results in a map.

The classification function maps elements to some key type K. The collector produces a map[K][]T whoses keys are value resulting from applying the classification function to the input elements which map to the associated key under the classification function.

func JoiningCollector

func JoiningCollector(
	sep string,
) *Collector[string, *[]string, string]

JoiningCollector returns a Collector that concatenates the input elements into a string, in encounter order.

func MappingCollector

func MappingCollector[T, U, A, R any](
	mapper function.Function[T, U],
	downstream *Collector[U, A, R]) *Collector[T, A, R]

MappingCollector adapts a Collector accepting elements of type U to one accepting elements of type T by appling a mapping function to each input element before accumulation.

func MaxByCollector

func MaxByCollector[T any](
	less Less[T],
) *Collector[T, *Optional[T], *Optional[T]]

MaxByCollector returns a Collector that produces the maximal element according to a given Less, described as an *Optional[T].

func MinByCollector

func MinByCollector[T any](
	less Less[T],
) *Collector[T, *Optional[T], *Optional[T]]

MinByCollector returns a Collector that produces the minimal element according to a given Less, described as an *Optional[T].

func PartitioningByCollector

func PartitioningByCollector[T, D, A any](
	predicate function.Predicate[T],
	downstream *Collector[T, A, D],
) *Collector[T, *[2]A, map[bool]D]

PartitioningByCollector returs a Collector which partitions the input elements according to a Predicate, reduces the values in each partition according to antoher Collector, and organizes them into map[bool]D whose values are the result of the downstream reducation.

func PartitioningByToSliceCollector

func PartitioningByToSliceCollector[T any](
	predicate function.Predicate[T],
) *Collector[T, *[2]*[]T, map[bool][]T]

PartitioningByToSliceCollector returns a Collector which partitions the input elements according to a Predicated, and organizes them into a map[bool][]T.

func ReducingCollector

func ReducingCollector[T any](
	identity T,
	op function.BinaryOperator[T],
) *Collector[T, *T, T]

ReducingCollector returns a Collector which performs a reduction of its input elements under a specified BinaryOperator using the provided identity.

func ReducingToOptionalCollector

func ReducingToOptionalCollector[T any](
	op function.BinaryOperator[T],
) *Collector[T, *Optional[T], *Optional[T]]

func SummarizingCollector

func SummarizingCollector[T any, R Number](
	mapper function.Function[T, R],
) *Collector[T, *SummaryStatistics[R], *SummaryStatistics[R]]

SummarizingCollector returns a Collector which applies an number-producing mapping function to each input element, and returns summary statistics for the resulting values.

func SummingCollector

func SummingCollector[T any, R Number](
	mapper function.Function[T, R],
) *Collector[T, *R, R]

SummingCollector returns a Collector that produces the sum of a number-valued function applied to the input elements. If no elements are present, the result is 0.

func ToMapCollector

func ToMapCollector[T any, K comparable, U any](
	keyMapper function.Function[T, K],
	valueMapper function.Function[T, U],
	mergeFunction function.BinaryOperator[U],
) *Collector[T, map[K]U, map[K]U]

ToMapCollector returns a Collector that accumulates elements into a map[K]U whose keys and values are the result of applying the provided mapping functions to the input elements.

If mapped keys contains duplicates, the value mapping function is applied to each equal element, and the results are merged using the provided merging function.

func ToSetCollector

func ToSetCollector[T comparable]() *Collector[T, map[T]bool, map[T]bool]

ToSetCollector returns a Collector that accumulates the input elements into a new map[T]bool.

func ToSliceCollector

func ToSliceCollector[T any]() *Collector[T, *[]T, []T]

ToSliceCollector returns a Collector that accumulates the input elements into a new slice.

func ToUniqueKeysMapCollector

func ToUniqueKeysMapCollector[T any, K comparable, U any](
	keyMapper function.Function[T, K],
	valueMapper function.Function[T, U],
) *Collector[T, map[K]U, map[K]U]

ToUniqueKeysMapCollector returns a Collector that accumulate elements into a map[K]U whose keys and values are the result of applying the provided mapping functions to the input elements.

If the mapped keys contains duplicates, this function panics.

func (*Collector[T, A, R]) Accumulator

func (c *Collector[T, A, R]) Accumulator() function.BiConsumer[A, T]

Accumulator is a function that folds a value into a mutable result container.

func (*Collector[T, A, R]) Combiner

func (c *Collector[T, A, R]) Combiner() function.BinaryOperator[A]

Combiner is a function that accepts two partial results and merges them. The combiner function may fold state from one argument into the other and return that, or may return a new result container.

func (*Collector[T, A, R]) Finisher

func (c *Collector[T, A, R]) Finisher() function.Function[A, R]

Finisher performs the final transformation from the intermediate accumulation type A to the final result Type R

func (*Collector[T, A, R]) Supplier

func (c *Collector[T, A, R]) Supplier() function.Supplier[A]

Supplier is a function that creates and returns a new mutable result container.

type Comparable

type Comparable[T any] interface {
	CompareTo(o T) int
}

type Less

type Less[T any] func(t1, t2 T) bool

Less is a comparison function.

type Number

type Number interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | ~float32 | ~float64
}

type Optional

type Optional[T any] struct {
	// contains filtered or unexported fields
}

Optional is a container object which may or may not contain a value. If a value is present, IsPresent() returns true, if no value is present, the object is considered empty and IsPresent() returns false. The zero value for Optional is an empty object ready to use.

func Max

func Max[T Number](
	stream Stream[T],
) *Optional[T]

Max returns the maximum element of a stream.

func Min

func Min[T Number](
	stream Stream[T],
) *Optional[T]

Min returns the minimum element of a stream.

func OptionalEmpty

func OptionalEmpty[T any]() *Optional[T]

OptionalEmtpy returns an empty Optional instance. No value is present for this Optional.

func OptionalFlatMap

func OptionalFlatMap[U, T any](
	o *Optional[T],
	mapper function.Function[T, *Optional[U]],
) *Optional[U]

OptionalFlagMap returns the result of applying the give Optional-bearing mapping function to a value, otherwise returns an empty Optional

func OptionalMap

func OptionalMap[U, T any](
	o *Optional[T],
	mapper function.Function[T, U],
) *Optional[U]

OptionalMap returns the result applying the give mapping function to a value if the value is present, otherwise returns an empty Optional

func OptionalOf

func OptionalOf[T any](value T) *Optional[T]

OptionalOf returns an Optional describing the give value.

func (*Optional[T]) Filter

func (o *Optional[T]) Filter(predicate function.Predicate[T]) *Optional[T]

Filter returns an Optional describing a value if the value is present and the value matches the give predicate, otherwise returns an empty Optional.

func (*Optional[T]) Get

func (o *Optional[T]) Get() T

Get returns the value if it is presen. Otherwise, Get panics.

func (*Optional[T]) IfPresent

func (o *Optional[T]) IfPresent(action function.Consumer[T])

IfPresent performs the give action with a value if the value is present, otherwise does nothing.

func (*Optional[T]) IfPresentOrElse

func (o *Optional[T]) IfPresentOrElse(
	action function.Consumer[T],
	emptyAction func(),
)

IfPresentOrElese performs the give action with a value if the value is present, otherwise performs the given empyAction.

func (*Optional[T]) IsEmpty

func (o *Optional[T]) IsEmpty() bool

IsEmpty returns true if a value is not present, otherwise true

func (*Optional[T]) IsPresent

func (o *Optional[T]) IsPresent() bool

IsPresent returns true if a value is present, otherwise false.

func (*Optional[T]) Or

func (o *Optional[T]) Or(supplier function.Supplier[*Optional[T]]) *Optional[T]

Or returns an Optional describing a value if the value is present, otherwise returns an Optional produced by the supplying function.

func (*Optional[T]) OrElse

func (o *Optional[T]) OrElse(other T) T

OrElse returns a value if the value is present, otherwise returns other.

func (*Optional[T]) OrElseGet

func (o *Optional[T]) OrElseGet(supplier function.Supplier[T]) T

OrElseGet returns a value if the value is present, othwrwise returns the result produced by the supplying function.

func (*Optional[T]) OrElsePanic

func (o *Optional[T]) OrElsePanic() T

OrElsePanic retruns a alue if the value is present, otherwise panics.

func (*Optional[T]) Stream

func (o *Optional[T]) Stream() Stream[T]

Stream returns a Stream containing only a value if the value is present, Otherwise returns an empty Stream.

func (*Optional[T]) String

func (o *Optional[T]) String() string

String returns a non-empty string representation of this Optional suitable for debugging. The exact presentation format is unspecified and mya vary between implementations and versions.

type Stream

type Stream[T any] interface {
	BaseStream[T]

	// Parallel returns an equivalent stream that is parallel. May return
	// itself, either because the stream was alreay parallel, or because
	// the underlying stream state was modified to be parallel.
	Parallel() Stream[T]

	// Filter returns a stream consisting of the elements of this stream
	// that match given predicate.
	Filter(predicate function.Predicate[T]) Stream[T]

	// Sorted returns a stream consisting of the elements of this stream,
	// according to the provided Less.
	Sorted(cmp func(a, b T) int) Stream[T]

	// 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 steam.
	Peek(action function.Consumer[T]) Stream[T]

	// Limit returns a stream consisting of the elements of this stream,
	// truncated to be no logner than maxSize in length.
	Limit(maxSize int) Stream[T]

	// Skip returns a stream consisting of the remaining elements of this
	// stream after discarding the first n elements of the stream.
	// If this stream contians fewer than n elements then an empty stream
	// will be returned.
	Skip(n int) Stream[T]

	// ForEach performs an action for each element of this stream.
	ForEach(action function.Consumer[T])

	// ToSlice returns a slice containing the elements of this stream.
	ToSlice() []T

	// Reduce performs a reduction on the elements of this stream, using
	// the provided identity value and an accumulation function, and returns
	// the reduced value.
	Reduce(identity T, accumulator function.BinaryOperator[T]) T

	// ReduceToOptional performs a reduction on the elements of this strem,
	// using an associative accumulation function, and returns an Optional
	// describing the reduced value, if nay.
	ReduceToOptional(accumulator function.BinaryOperator[T]) *Optional[T]

	// Min returns the minimum element of this stream according to the
	// provided Less.
	Min(Less Less[T]) *Optional[T]

	// Max returns the maximum element of this stream according to the
	// provided Less.
	Max(less Less[T]) *Optional[T]

	// Count returns the count of elements in this stream.
	Count() int

	// AnyMatch returns whether any elements of this stream match the provided
	// predicate. May not evaluate the predicate on all elements if not
	// necesary for determining the resulst. If the stream is empty then false
	// is returned and the predicate is not evaluated.
	AnyMatch(predicate function.Predicate[T]) bool

	// AllMatch returns whether all elements of this stream match the provided
	// predicated. May not evaluate the predicate on all elements if not
	// necessary. If the stream is empty then true is returned and the
	// predicate is not evaluated.
	AllMatch(predicate function.Predicate[T]) bool

	// NoneMatch returns whether no elements of this stream match the provide
	// predicate. May not evaluate the predicate on all elements if not
	// necessary for determing the result. If the stream is empty then true is
	// returned and predicate is not evaluated.
	NoneMatch(predicate function.Predicate[T]) bool

	// FindFirst returns an Optional describing the first element of this
	// stream or an empty Optional if the stream is empty.
	FindFirst() *Optional[T]

	// FindAny returns an Optional describing some element of the stream, or
	// an empty Optional if the steam is empty.
	//
	// The behavior of this operation is explicitly nondeterministic; it is
	// free to select any element in the stream. This is to allow for maximal
	// performance in parallel operations; the cost is that multiple
	// invocations on the same source many not return the same result. (If a
	// stable result is desired, use FindFirst instead.
	FindAny() *Optional[T]
}

func Concat

func Concat[T any](a, b Stream[T]) Stream[T]

Concat a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.

func Distinct

func Distinct[T comparable](stream Stream[T]) Stream[T]

Distinct returns a stream consisting of the distinct elements (according to ==) of this stream.

func Empty

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

Empty returns an empty Stream

func FileLines

func FileLines(filepath string) (Stream[string], error)

func FlatMap

func FlatMap[T, R any](
	stream Stream[T],
	mapper function.Function[T, Stream[R]],
) Stream[R]

FlatMap returns a stream consisting of the results of replacing each element of stream with the contents of mapped stream produced by applying the provided mapping function to each element.

func Generate

func Generate[T any](s function.Supplier[T]) Stream[T]

Generate returns an infinite sequential unordered stream where each element is generated by the provided Supplier. This is suitable for generating constant streams, streams of random elements, etc.

func Iterate

func Iterate[T any](seed T, f function.UnaryOperator[T]) Stream[T]

Iterate returns an infinite sequential ordered Stream produces by iterative appliation of a function f to an initial element seed, producing a Stream consisiting of seed, f(seed), f(f(seed)), etc.

func IterateN

func IterateN[T any](
	seed T,
	hasNext function.Predicate[T],
	next function.UnaryOperator[T]) Stream[T]

IterateN returns a sequential ordered Stream produced by iterative application of the given next function to an initial element, conditioned on satisfying the given code hasNext predicate. stream terminates as soon as the code hasNext predicate returns false.

func Map

func Map[T, R any](stream Stream[T], mapper function.Function[T, R]) Stream[R]

Map returns a stream consisting of the results of applying the given function to the elements of the given stream.

func Of

func Of[T any](data ...T) Stream[T]

Returns a sequential ordered stream whose elements are the specified values.

func Range

func Range[T Number](
	startInclusive T,
	endExclusive T,
) Stream[T]

Range returns a sequential ordered Stream from startInclusive to endExclusive (exclusive) by an incremental step of 1.

func RangeClosed

func RangeClosed[T Number](
	startInclusive T,
	endInclusive T,
) Stream[T]

RangeClosed returns a sequential ordered Stream from staticInclusive to endInclusive (inclusive) by an incremental step of 1.

func Sorted

func Sorted[T cmp.Ordered](stream Stream[T]) Stream[T]

Sorted returns a stream consisting of the elements of stream, sorted according to natural order.

type SummaryStatistics

type SummaryStatistics[T Number] struct {
	// contains filtered or unexported fields
}

func NewSummaryStatistics

func NewSummaryStatistics[T Number]() *SummaryStatistics[T]

func (*SummaryStatistics[T]) GetAverage

func (i *SummaryStatistics[T]) GetAverage() float64

func (*SummaryStatistics[T]) GetCount

func (i *SummaryStatistics[T]) GetCount() int64

func (*SummaryStatistics[T]) GetMax

func (i *SummaryStatistics[T]) GetMax() int64

func (*SummaryStatistics[T]) GetMin

func (i *SummaryStatistics[T]) GetMin() int64

func (*SummaryStatistics[T]) GetSum

func (i *SummaryStatistics[T]) GetSum() int64

func (*SummaryStatistics[T]) String

func (i *SummaryStatistics[T]) String() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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