Java 8 的 Stream 接口处理集合数据转换特别好用,之前写过《自己实现 Java8 的 Stream 流(串行版)》,现在工作语言主要使用 Go 了,所以用 Go 也实现了一遍,可以使用 go get github.com/youthlin/stream
引入。先看个使用示例吧:
// example_test.go
func ExampleStream_Filter() {
stream.Of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9).
Filter(func(e types.T) bool {
// 没有范型只能通过 e.(int) 的形式强制转换
return e.(int)%3 == 0
}).
ForEach(func(e types.T) {
fmt.Println(e)
})
// Output:
// 0
// 3
// 6
// 9
}
func ExampleStream_Map() {
stream.IntRange(0, 5).
Map(func(t types.T) types.R {
return fmt.Sprintf("<%d>", t)
}).
ForEach(func(t types.T) {
fmt.Printf("%v", t)
})
// Output:
// <0><1><2><3><4>
}