Go Stream, like Java 8 Stream.

Overview

Go Stream

PkgGoDev Go Report Card Build Status codecov

Go Stream, like Java 8 Stream.

Blog Post: https://youthlin.com/?p=1755

How to get

go get github.com/youthlin/stream

国内镜像: https://gitee.com/youthlin/stream
go.mod 中引入模块路径 github.com/youthlin/stream 及版本后,
再添加 replace 即可:

// go.mod

require github.com/youthlin/stream latest

replace github.com/youthlin/stream latest => gitee.com/youthlin/stream latest

Play online

https://play.golang.org/p/nPQJYqA3-Jr

", e) return m }) fmt.Println(m) // Output: // map[0:<0> 4:<4> 8:<8> 12:<12> 16:<16>] } ">
package main

import (
	"fmt"

	"github.com/youthlin/stream"
	"github.com/youthlin/stream/types"
)

func main() {
	m := stream.IntRange(0, 10).
		Filter(func(e types.T) bool {
			return e.(int)%2 == 0
		}).
		Map(func(e types.T) types.R {
			return e.(int) * 2
		}).
		ReduceWith(map[int]string{}, func(acc types.R, e types.T) types.R {
			m := acc.(map[int]string)
			m[e.(int)] = fmt.Sprintf("<%d>", e)
			return m
		})
	fmt.Println(m)
	// Output:
	// map[0:<0> 4:<4> 8:<8> 12:<12> 16:<16>]
}

Examples

", e) }). ForEach(func(e types.T) { fmt.Printf("%s,", e) }) // Output: // 1,2,3,4,,, } func ExampleOfMap() { var m1 = map[int]string{ 3: "c", 2: "b", 1: "a", } s := stream.OfMap(m1). Map(func(e types.T) types.R { p := e.(types.Pair) p.First, p.Second = p.Second, p.First return p }). Sorted(func(left types.T, right types.T) int { p1 := left.(types.Pair) p2 := right.(types.Pair) return p1.Second.(int) - p2.Second.(int) }). ToSlice() fmt.Println(s) stream.OfMap(nil).ForEach(func(e types.T) { fmt.Println("not print") }) // Output: // [{a 1} {b 2} {c 3}] } func ExampleStream_Filter() { stream.Of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9). Filter(func(e types.T) bool { 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.(int)) }). ForEach(func(t types.T) { fmt.Printf("%v", t) }) // Output: // <0><1><2><3><4> } func ExampleStream_FlatMap() { stream.Of([]int{0, 2, 4, 6, 8}, []int{1, 3, 5, 7, 9}). FlatMap(func(t types.T) stream.Stream { return stream.Of(stream.Slice(t)...) }). ForEach(func(t types.T) { fmt.Printf("%d", t) }) // Output: // 0246813579 } func ExampleStream_Sorted() { stream.IntRange(1, 10). Sorted(types.ReverseOrder(types.IntComparator)). ForEach(func(t types.T) { fmt.Printf("%d,", t) }) // Output: // 9,8,7,6,5,4,3,2,1, } func TestToMap(t *testing.T) { m := stream.IntRange(0, 10).ReduceWith(make(map[int]int), func(acc types.R, t types.T) types.R { acc.(map[int]int)[t.(int)] = t.(int) * 10 return acc }) t.Log(m) // Output: // map[0:0 1:10 2:20 3:30 4:40 5:50 6:60 7:70 8:80 9:90] } ">
type Stream interface {
	// stateless operate 无状态操作

	Filter(types.Predicate) Stream         // 过滤
	Map(types.Function) Stream             // 转换
	FlatMap(func(t types.T) Stream) Stream // 打平
	Peek(types.Consumer) Stream            // peek 每个元素

	// stateful operate 有状态操作

	Distinct(types.IntFunction) Stream // 去重
	Sorted(types.Comparator) Stream    // 排序
	Limit(int64) Stream                // 限制个数
	Skip(int64) Stream                 // 跳过个数

	// terminal operate 终止操作

	// 遍历
	ForEach(types.Consumer)
	// return []T 转为切片
	ToSlice() []types.T
	// return []X which X is the type of some
	ToElementSlice(some types.T) types.R
	// return []X which X is same as the `typ` representation
	ToSliceOf(typ reflect.Type) types.R
	// 测试是否所有元素满足条件
	AllMatch(types.Predicate) bool
	// 测试是否没有元素满足条件
	NoneMatch(types.Predicate) bool
	// 测试是否有任意元素满足条件
	AnyMatch(types.Predicate) bool
	// Reduce return optional.Empty if no element. calculate result by (T, T) -> T from first element
	Reduce(accumulator types.BinaryOperator) optional.Optional
	// type of initValue is same as element.  (T, T) -> T
	ReduceFrom(initValue types.T, accumulator types.BinaryOperator) types.T
	// type of initValue is different from element. (R, T) -> R
	ReduceWith(initValue types.R, accumulator func(types.R, types.T) types.R) types.R
	FindFirst() optional.Optional
	// 返回元素个数
	Count() int64
}


func ExampleOf() {
	fmt.Println(stream.Of().Count())
	fmt.Println(stream.Of(1).Count())
	fmt.Println(stream.Of("a", "b").Count())
	var s = []int{1, 2, 3, 4}
	stream.Of(stream.Slice(s)...).ForEach(func(t types.T) {
		fmt.Printf("%d,", t)
	})
	// Output:
	// 0
	// 1
	// 2
	// 1,2,3,4,
}

func ExampleOfSlice() {
	var intArr = []int{1, 2, 3, 4}
	stream.OfSlice(intArr).ForEach(func(e types.T) {
		fmt.Printf("%d,", e)
	})
	var nilArr []int
	stream.OfSlice(nilArr).ForEach(func(e types.T) {
		fmt.Printf("should not print")
	})
	var strArr = []string{"a", "b"}
	stream.OfSlice(strArr).
		Map(func(e types.T) types.R {
			return fmt.Sprintf("<%s>", e)
		}).
		ForEach(func(e types.T) {
			fmt.Printf("%s,", e)
		})
	// Output:
	// 1,2,3,4,,,
}

func ExampleOfMap() {
	var m1 = map[int]string{
		3: "c",
		2: "b",
		1: "a",
	}
	s := stream.OfMap(m1).
		Map(func(e types.T) types.R {
			p := e.(types.Pair)
			p.First, p.Second = p.Second, p.First
			return p
		}).
		Sorted(func(left types.T, right types.T) int {
			p1 := left.(types.Pair)
			p2 := right.(types.Pair)
			return p1.Second.(int) - p2.Second.(int)
		}).
		ToSlice()
	fmt.Println(s)
	stream.OfMap(nil).ForEach(func(e types.T) {
		fmt.Println("not print")
	})
	// Output:
	// [{a 1} {b 2} {c 3}]
}

func ExampleStream_Filter() {
	stream.Of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9).
		Filter(func(e types.T) bool {
			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.(int))
		}).
		ForEach(func(t types.T) {
			fmt.Printf("%v", t)
		})
	// Output:
	// <0><1><2><3><4>
}
func ExampleStream_FlatMap() {
	stream.Of([]int{0, 2, 4, 6, 8}, []int{1, 3, 5, 7, 9}).
		FlatMap(func(t types.T) stream.Stream {
			return stream.Of(stream.Slice(t)...)
		}).
		ForEach(func(t types.T) {
			fmt.Printf("%d", t)
		})
	// Output:
	// 0246813579
}
func ExampleStream_Sorted() {
	stream.IntRange(1, 10).
		Sorted(types.ReverseOrder(types.IntComparator)).
		ForEach(func(t types.T) {
			fmt.Printf("%d,", t)
		})
	// Output:
	// 9,8,7,6,5,4,3,2,1,
}
func TestToMap(t *testing.T) {
	m := stream.IntRange(0, 10).ReduceWith(make(map[int]int), func(acc types.R, t types.T) types.R {
		acc.(map[int]int)[t.(int)] = t.(int) * 10
		return acc
	})
	t.Log(m)
	// Output:
	// map[0:0 1:10 2:20 3:30 4:40 5:50 6:60 7:70 8:80 9:90]
}

Change Log

  • v0.0.3 2020-12-08 add factory method: OfInts, OfInt64s, OfFloat32s, OfFloat64s, OfStrings;
    add Stream method: ReduceBy
  • v0.0.2 2020-12-07 add factory method: OfSlice, OfMap
  • v0.0.1 2020-11-12 first version

Todo

  • add Benchmark test
  • support parallel stream
You might also like...
An application written in Go to generate fractals like the Mandelbrot set and the Julia set.
An application written in Go to generate fractals like the Mandelbrot set and the Julia set.

Fractals An application written in Go to generate fractals like the Mandelbrot set and the Julia set. Screenshots Mandelbrot set Julia set Prerequisit

Quicat -- a socat-like utility for working with QUIC

Quicat -- a socat-like utility for working with QUIC This is a utility that I occasionally use for building secure-enough tunnels on flaky connections

Go Collection Stream API, inspired in Java 8 Stream.

GoStream gostream 是一个数据流式处理库。它可以声明式地对数据进行转换、过滤、排序、分组、收集,而无需关心操作细节。 Changelog 2021-11-18 add ToSet() collector Roadmap 移除go-linq依赖 Get GoStream go get

A go module supply Java-Like generic stream programming (while do type check at runtime)

gostream A go module supplying Java-Like generic stream programming (while do type check at runtime) Using Get a Stream To get a Stream, using SliceSt

Aes for go and java; build go fo wasm and use wasm parse java response.

aes_go_wasm_java aes for go and java; build go fo wasm and use wasm parse java response. vscode setting config settings.json { "go.toolsEnvVars":

Update-java-ca-certificates - Small utility to convert the system trust store to a system Java KeyStore

update-java-ca-certificates This small utility takes care of creating a system-w

A Cloud Native Buildpack that contributes SDKMAN and uses it to install dependencies like the Java Virtual Machine

gcr.io/paketo-buildpacks/sdkman A Cloud Native Buildpack that contributes SDKMAN and uses it to install dependencies like the Java Virtual Machine. Be

GoBatch is a batch processing framework in Go like Spring Batch in Java
GoBatch is a batch processing framework in Go like Spring Batch in Java

GoBatch English|中文 GoBatch is a batch processing framework in Go like Spring Batch in Java. If you are familiar with Spring Batch, you will find GoBat

Moviefetch: a simple program to search and download for movies from websites like 1337x and then stream them

MovieFetch Disclaimer I am NOT responisble for any legal issues or other you enc

bluemonday: a fast golang HTML sanitizer (inspired by the OWASP Java HTML Sanitizer) to scrub user generated content of XSS

bluemonday bluemonday is a HTML sanitizer implemented in Go. It is fast and highly configurable. bluemonday takes untrusted user generated content as

XSD (XML Schema Definition) parser and Go/C/Java/Rust/TypeScript code generator

xgen Introduction xgen is a library written in pure Go providing a set of functions that allow you to parse XSD (XML schema definition) files. This li

Golang-Haxe-CPP/CSharp/Java/JavaScript transpiler

TARDIS Go - Haxe transpiler Haxe - C++ / C# / Java / JavaScript Project status: a non-working curiosity, development currently on-ice The advent of

Instant messaging platform. Backend in Go. Clients: Swift iOS, Java Android, JS webapp, scriptable command line; chatbots
Instant messaging platform. Backend in Go. Clients: Swift iOS, Java Android, JS webapp, scriptable command line; chatbots

Tinode Instant Messaging Server Instant messaging server. Backend in pure Go (license GPL 3.0), client-side binding in Java, Javascript, and Swift, as

Java properties scanner for Go

Overview Please run git pull --tags to update the tags. See below why. properties is a Go library for reading and writing properties files. It support

minectl 🗺 is a cli for creating Minecraft (java or bedrock) server on different cloud provider.

minectl 🗺 minectl️️ is a cli for creating Minecraft (java or bedrock) server on different cloud provider. It is a private side project of me, to lear

jacobin - A more than minimal JVM written in Go and capable of running Java 11 bytecode.

This overview gives the background on this project, including its aspirations and the features that it supports. The remaining pages discuss the basics of JVM operation and, where applicable, how Jacobin implements the various steps, noting any items that would be of particular interest to JVM cognoscenti.

Super Java Vulnerability Scanner
Super Java Vulnerability Scanner

XiuScan 不完善,正在开发中 介绍 一个纯Golang编写基于命令行的Java框架漏洞扫描工具 致力于参考xray打造一款高效方便的漏扫神器 计划支持Fastjson、Shiro、Struts2、Spring、WebLogic等框架 PS: 取名为XiuScan因为带我入安全的大哥是修君 特点

Cake is a lightweight HTTP client library for GO, inspired by Java Open-Feign.

Cake is a lightweight HTTP client library for GO, inspired by Java Open-Feign. Installation # With Go Modules, recommanded with go version 1.16

convert curl commands to Python, JavaScript, Go, PHP, R, Dart, Java, MATLAB, Rust, Elixir and more
convert curl commands to Python, JavaScript, Go, PHP, R, Dart, Java, MATLAB, Rust, Elixir and more

curlconverter curlconverter transpiles curl commands into programs in other programming languages. $ curlconverter --data "Hello, world!" example.com

Releases(v0.0.3)
Owner
Youth.霖
富强 民主 文明 和谐; 自由 平等 公正 法治; 爱国 敬业 诚信 友善。
Youth.霖
A super simple Lodash like utility library with essential functions that empowers the development in Go

A simple Utility library for Go Go does not provide many essential built in functions when it comes to the data structure such as slice and map. This

Rahul Baruri 131 Sep 15, 2022
Creates Prometheus Metrics for PolicyReports and ClusterPolicyReports. It also sends PolicyReportResults to different Targets like Grafana Loki or Slack

PolicyReporter Motivation Kyverno ships with two types of validation. You can either enforce a rule or audit it. If you don't want to block developers

Frank Jogeleit 0 Aug 6, 2021
Helpfully Functional Go like underscore.js

/\ \ __ __ ___ \_\ \ __ _ __ ____ ___ ___ _ __ __ __ __

null 382 Sep 19, 2022
🔍 A jq-like tool that queries files via glob.

?? fq A jq-like tool that queries files via glob. ✅ Prerequisites Go 1.17+ jq (installed and on PATH) ?? Installation $ go get github.com/siketyan/fq

Naoki Ikeguchi 5 Dec 22, 2021
A fully Go userland with Linux bootloaders! u-root can create a one-binary root file system (initramfs) containing a busybox-like set of tools written in Go.

u-root Description u-root embodies four different projects. Go versions of many standard Linux tools, such as ls, cp, or shutdown. See cmds/core for m

null 2k Sep 23, 2022
generate random data like name, email, uuid, address, images and etc.

gg-rand generate random data like name, email, uuid, address, images and etc. build and install: make run: gg-rand $ gg-rand SillyName : Knavesa

bingoohuang 2 Mar 13, 2022
Like tools/cmd/stringer with bitmask features

Bitmasker Bitmasker is a tool used to automate the creation of helper methods when dealing with bitmask-type constant flags. Given the name of an unsi

Go Curses 0 Nov 25, 2021
Experimenting with golang generics to implement functional favorites like filter, map, && reduce.

funcy Experimenting with golang generics to implement functional favorites like filter, map, && reduce. 2021-12 To run the tests, you need to install

null 0 Dec 29, 2021
CDN-like in-memory cache with shielding, and Go 1.18 Generics

cache CDN-like, middleware memory cache for Go applications with integrated shielding and Go 1.18 Generics. Usage package main import ( "context" "

Alex 0 Apr 26, 2022
A go1.18+ package to (maybe) simplify performing operations on slices in a fluent-like style.

sop ✨ W.I.P. ✨ sop (slices operation) is a go1.18+ package to (maybe) simplify performing operations on slices in a fluent-like style with common oper

Ringo Hoffmann 3 Mar 17, 2022