Skip to content

Instantly share code, notes, and snippets.

@bserdar
Created Oct 26, 2018
Embed
What would you like to do?
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