Skip to content

Instantly share code, notes, and snippets.

@bserdar
Created October 26, 2018 03:41
Show Gist options
  • Save bserdar/45faad78a473a694d893c1f9a7928448 to your computer and use it in GitHub Desktop.
Save bserdar/45faad78a473a694d893c1f9a7928448 to your computer and use it in GitHub Desktop.
Java stream lookalike in Go
package main

import (
	"fmt"
)

type Stream func() (int,bool)

func (s Stream) Filter(pred func(int) bool) Stream {
   return func() (int,bool) {
      for {
        v, ok:=s()
        if !ok {
           return 0,false
        }
        if pred(v) {
          return v,true
        }
      }
   }
}

func (s Stream) ForEach(f func(int) bool) {
  for {
    v, ok:=s()
    if !ok {
       break
    }
    if !f(v) {
       break
    }
  }
}

func Iterator(arr []int) Stream {
   i:=0
   return func() (int,bool) {
      if i>len(arr)-1 {
         return 0,false
      }
      ret:=arr[i]
      i++
      return ret,true
    }
}


func main() {
        i:=[]int{1,2,3,4,5}
        Iterator(i).Filter(func(i int) bool {return i>2}).ForEach(func(v int) bool {
    	     fmt.Printf("%d ",v)
	     return true
	  })
	
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment