ForEach function

This commit is contained in:
Zane.Y 2017-07-15 11:53:28 +08:00
parent 430c95659d
commit 00fee0cddd
2 changed files with 42 additions and 1 deletions

View File

@ -1,9 +1,10 @@
package main package main
import ( import (
"fmt"
. "github.com/go-func/stream" . "github.com/go-func/stream"
"github.com/go-func/stream/collectors" "github.com/go-func/stream/collectors"
"fmt"
) )
func main() { func main() {
@ -47,6 +48,9 @@ func main() {
.Collect(&collectors.SummarizingFloat64{Mapper: func(item interface{}) float64 { .Collect(&collectors.SummarizingFloat64{Mapper: func(item interface{}) float64 {
return float64(item.(int)) return float64(item.(int))
}}) }})
.ForEach(func(item interface{}) {
fmt.Println(item)
})
*/ */
fmt.Println(tmp) fmt.Println(tmp)
} }

37
stream/forEach.go Normal file
View File

@ -0,0 +1,37 @@
package stream
import "runtime"
//ForEach 对任意数组操作,针对每个元素执行一遍指定的行为
func (s *Stream) ForEach(action func(interface{})) {
if s.isParallel {
count := runtime.NumCPU()
ch1 := make(chan interface{}, count)
ch2 := make(chan interface{})
for i := 0; i < count; i++ {
go func() {
for true {
if value, ok := <-ch1; !ok {
break
} else {
action(value)
}
}
ch2 <- 0
}()
}
go func() {
for _, v := range s.list {
ch1 <- v
}
close(ch1)
}()
for i := 0; i < count; i++ {
<-ch2
}
} else {
for _, v := range s.list {
action(v)
}
}
}