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 github.com/a3d21/gostream

Example

See walkthrough.go

Base Example

5 }).SortedBy(func(it interface{}) interface{} { return it }).Collect(ToSlice([]int(nil))) if !reflect.DeepEqual(got, want) { panic(fmt.Sprintf("%v != %v", got, want)) } // walkthrough() } ">
package main

import (
	"fmt"
	"reflect"

	. "github.com/a3d21/gostream/core"
)

func main() {
	input := []int{4, 3, 2, 1}
	want := []int{6, 8}

	got := From(input).Map(func(it interface{}) interface{} {
		return 2 * it.(int)
	}).Filter(func(it interface{}) bool {
		return it.(int) > 5
	}).SortedBy(func(it interface{}) interface{} {
		return it
	}).Collect(ToSlice([]int(nil)))

	if !reflect.DeepEqual(got, want) {
		panic(fmt.Sprintf("%v != %v", got, want))
	}

	// walkthrough()
}

Map & FlatMap

Map和FlatMap的差别在于:FlatMap的mapper返回一个Stream。

input := [][]int{{3, 2, 1}, {6, 5, 4}, {9, 8, 7}}
want := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
got := From(input).FlatMap(func(it interface{}) Stream {
   return From(it)
}).SortedBy(func(it interface{}) interface{} {
   return it
}).Collect(ToSlice([]int{}))

Collect ToSlice & ToMap

Collect将数据收集起来。受限于go的类型系统,需要显示传类型参数——一个目标类型的实例,可以为nil。

intput := []int{1, 2, 3, 4, 5}
identity := func(it interface{}) interface{} { return it }

// []int{1, 2, 3, 4, 5}
gotSlice := From(intput).Collect(ToSlice([]int{}))
// map[int]int{1: 1, 2: 2, 3: 3, 4: 4, 5: 5}
gotMap := From(intput).Collect(ToMap(map[int]int(nil), identity, identity))

Collect GroupBy

GroupBy定义一个分组收集器,参数依序分别为 类型参数、分类方法、下游收集器。 GroupBy可以和ToSlice、ToMap组合,GroupBy也可以多级嵌套,实现多级分组。

GroupBy(typ interface{}, classifier normalFn, downstream collector) collector

假设一组货物,需要按Status,Location进行分组,目标类型为 map[int]map[string][]*Cargo。

// Cargo 货物实体
type Cargo struct {
   ID       int
   Name     string
   Location string
   Status   int
}

input := []*Cargo{{
    ID:       1,
    Name:     "foo",
    Location: "shenzhen",
    Status:   1,
    }, {
    ID:       2,
    Name:     "bar",
    Location: "shenzhen",
    Status:   0,
    }, {
    ID:       3,
    Name:     "a3d21",
    Location: "guangzhou",
    Status:   1,
}}
getStatus := func(it interface{}) interface{} { return it.(*Cargo).Status }
getLocation := func(it interface{}) interface{} { return it.(*Cargo).Location }

// result type: map[int]map[string][]*Cargo
got := From(input).Collect(
   GroupBy(map[int]map[string][]*Cargo(nil), getStatus,
      GroupBy(map[string][]*Cargo(nil), getLocation,
         ToSlice([]*Cargo(nil)))))

Flatten Group

这个示例演示如何将多级分组Map转成Slice。map[int]map[string][]*Cargo => []*Cargo

From(cargoByLocationByTo).FlatMap(func(it interface{}) Stream {
   return From(it.(KeyValue).Value).FlatMap(func(it2 interface{}) Stream {
      return From(it2.(KeyValue).Value)
   })
}).Collect(ToSlice([]*Cargo{}))

Benchmark

$ go test -bench .
goos: darwin
goarch: amd64
pkg: github.com/a3d21/gostream
cpu: Intel(R) Core(TM) i7-1068NG7 CPU @ 2.30GHz
BenchmarkToSliceRaw-8                       9064            130558 ns/op
BenchmarkToSliceStreamForeach-8              724           1729650 ns/op
BenchmarkCollectToSlice-8                    100          10976960 ns/op
BenchmarkCollectToSliceV2-8                  356           3442700 ns/op
BenchmarkLinqToSlice-8                       369           3233192 ns/op
BenchmarkToMapRaw-8                          169           7029026 ns/op
BenchmarkCollectToMap-8                       96          12598103 ns/op
BenchmarkCollectToMapV2-8                     87          12358812 ns/op
BenchmarkLinqToMap-8                          84          12632280 ns/op
BenchmarkToSetRaw-8                          198           5979733 ns/op
BenchmarkCollectToSet-8                       91          11230164 ns/op
BenchmarkCollectToSetV2-8                    100          11303409 ns/op
BenchmarkLinqToSet-8                          96          11588965 ns/op
BenchmarkGroupByRaw-8                         90          13014776 ns/op
BenchmarkGroupBy-8                            22          47840903 ns/op
BenchmarkGroupByV2-8                           8         126779306 ns/op
BenchmarkLinqGroupBy-8                        18          63476018 ns/op
BenchmarkPartition-8                         198           6084481 ns/op
BenchmarkCountRaw-8                          850           1379226 ns/op
BenchmarkCount-8                             196           6036287 ns/op
BenchmarkCountV2-8                           865           1384256 ns/op
BenchmarkGroupCount-8                         31          34496447 ns/op
BenchmarkGroupCountV2-8                       14          87656078 ns/op
PASS
ok      github.com/a3d21/gostream       34.211s
Similar Resources

A collection of offensive Go packages inspired by different Go repositories.

A collection of offensive Go packages inspired by different Go repositories.

OffensiveGolang OffensiveGolang is a collection of offensive Go packs inspired by different repositories. Ideas have been taken from OffensiveGoLang a

Dec 23, 2022

mock server to aid testing the jaguar-java client API

stripe-mock stripe-mock is a mock HTTP server that responds like the real Stripe API. It can be used instead of Stripe's test mode to make test suites

Dec 24, 2021

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

Jan 1, 2023

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

Dec 30, 2022

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

Jan 6, 2023

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

Jan 7, 2023

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

Jan 3, 2023

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.

Dec 29, 2022

Super Java Vulnerability Scanner

Super Java Vulnerability Scanner

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

Dec 30, 2021

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

Jan 2, 2023

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

Jan 8, 2022

A library designed for hosting Minecraft: Java Edition listeners.

expresso A library designed for hosting Minecraft: Java Edition listeners. Features Hosting listeners. All handshake, status, and login state packets.

Jul 29, 2022

Chaosblade executor for chaos experiments on Java applications

Chaosblade executor for chaos experiments on Java applications

Chaosblade-exec-jvm: Chaosblade executor for chaos experiments on Java applications Introduction The project is a chaosblade executor based on jvm-san

Dec 16, 2022

grab busy Java thread

grab busy Java thread

BusyJavaThreadGraber 抓取最繁忙的 N 个 Java 线程,快速排查 java 程序的 cpu 问题,看看是哪个线程在作妖。 使用 安装 go git clone {ssh/http}, cd main, go build ./main -pid {java pid} -tick

Jan 19, 2022

A small server for verifing if a given java program is succeptibel to CVE-2021-44228

CVE-2021-44228-Test-Server A small server for verifing if a given java program is succeptibel to CVE-2021-44228 Usage Build the program using go build

Nov 9, 2022

Go - Haxe - JS Java C# C++ C Python Lua

Go -> Haxe -> JS Java C# C++ C Python Lua

go2hx Compile: Go - Haxe - Js, Lua, C#, C++, Java, C, Python warning: heavily experimental still a ways to go before an alpha. Come give feedback on

Dec 14, 2022

A minimalistic LDAP server that is meant for test vulnerability to JNDI+LDAP injection attacks in Java, especially CVE-2021-44228.

jndi-ldap-test-server This is a minimalistic LDAP server that is meant for test vulnerability to JNDI+LDAP injection attacks in Java, especially CVE-2

Oct 3, 2022

Java with Go interoperability?

Java with Go interoperability? Say, we have a java classes with a lot of code that can not reasonably be ported to golang. What do we do? We call java

Dec 16, 2021

Utility to safely fetch Java class files being served by LDAP servers. Includes deobfuscator for common Log4J URL obfuscation techniques

ldap-get Utility to safely fetch Java class files being served by LDAP servers,

Nov 9, 2022
DEPRECATED: Data collection and processing made easy.

This project is deprecated. Please see this email for more details. Heka Data Acquisition and Processing Made Easy Heka is a tool for collecting and c

Nov 30, 2022
DataKit is collection agent for DataFlux.

DataKit DataKit is collection agent for DataFlux Build Dependencies apt-get install gcc-multilib: for building oracle input apt-get install tree: for

Dec 29, 2022
Stream data into Google BigQuery concurrently using InsertAll() or BQ Storage.

bqwriter A Go package to write data into Google BigQuery concurrently with a high throughput. By default the InsertAll() API is used (REST API under t

Dec 16, 2022
Basic Crud operation api's in golang

Basic Crud operation api's in golang

Nov 9, 2021
Go Stream, like Java 8 Stream.

Go Stream, like Java 8 Stream.

Dec 1, 2022
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":

Dec 14, 2021
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

Dec 28, 2022
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

Jan 4, 2023
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

Oct 6, 2022
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

Jan 16, 2022