Skip to content

rookiecj/go-stream

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

67 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

go-stream

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.

How to use

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)
	})
}

Operations

There 3 main operations:

  • Builders
  • Intermediates
  • Terminals

Builders

Builder operations build a Stream from various sources like slice or array.

  • FromSlice
  • FromVar
  • FromChan (Experimental)
  • FromSource
  • Indexed - for indexed Source

Intermediate operations

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)
  • WithIndex add an example for Indexed Source

Terminal operations

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

TODO

  • 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