go-stream
is a Go
package to help processing stream of elements in more declarative manner.
Stream
uses iterator pattern for visiting each element of a stream.
It is lazy, which means the operations are not executed until terminal operation is called.
Install as follows:
go get github.com/rookiecj/go-stream
and uses as follows:
package main
import (
"fmt"
s "github.com/rookiecj/go-stream/stream"
)
type myStruct struct {
Name string
}
func main() {
arr := []myStruct{
{"a"},
{"bbb"},
{"c"},
{"dddd"},
{"e"},
{"fffff"},
{"g"},
{"hhhhh"},
{"i"},
}
s.FromSlice(arr).
Filter(func(v myStruct) bool {
return len(v.Name) == 1
}).
Map(func(v myStruct) myStruct {
return myStruct{v.Name + "!"}
}).
ForEach(func(ele myStruct) {
fmt.Println(ele)
})
}
There 3 main operations:
- Builders
- Intermediates
- Terminals
Builder operations build a Stream
from various sources like slice or array.
- FromSlice
- FromVar
- FromChan (Experimental)
- FromSource
- Indexed - for indexed
Source
Intermediate operations generate new stream which consume data from upstream and apply operator on it.
- Filter
- Map/MapAny,MapIndex/MapIndexAny
- FlatMapConcat/FlatMapConcatAny(Experimental)
- FlatMapConcurrent
- Take, Skip
- Distinct, DistinctBy
- ZipWith/ZipWithAny
- ZipWithPrev (Experimental)
- Scan/ScanAny
- Window
- OnRecover (Experimental)
-
WithIndexadd an example forIndexed
Source
Terminal operations are collectors which trigger streams to work. and return the result of the stream.
- ForEach, ForEachIndex
- Collect/CollectTo
- Reduce/ReduceAny
- Fold/FoldAny
- Find/FindIndex/FindLast
- All,Any
- Count
Slightly more type safe functions are:
- ForEachAs, ForEachIndex
- CollectAs, CollectTo
- CollectAsSafe, CollectionToSafe
- ReduceAs
- FoldAs
- FindOrAs
- make ToStream lazy
- add more Builders
- Stream to interface
- add more intermediate operations
- add more safe terminal operations
- add doc
- add unittest
- remove Source/Collector from Stream
- make it more functional