From 4947327ed6c809daed73ba5938bd54e3daca2336 Mon Sep 17 00:00:00 2001 From: Pei PeiDong Date: Wed, 2 Apr 2025 10:53:46 +0800 Subject: [PATCH] feat: add ToMap for stream --- stream/stream.go | 9 +++++++++ stream/stream_example_test.go | 19 +++++++++++++++++++ stream/stream_test.go | 23 +++++++++++++++++++++++ 3 files changed, 51 insertions(+) diff --git a/stream/stream.go b/stream/stream.go index d052aa0..15e4a0c 100644 --- a/stream/stream.go +++ b/stream/stream.go @@ -420,3 +420,12 @@ func (s Stream[T]) LastIndexOf(target T, equal func(a, b T) bool) int { func (s Stream[T]) ToSlice() []T { return s.source } + +func ToMap[T any, K comparable, V any](s Stream[T], mapper func(item T) (K, V)) map[K]V { + result := map[K]V{} + for _, v := range s.source { + k, v := mapper(v) + result[k] = v + } + return result +} diff --git a/stream/stream_example_test.go b/stream/stream_example_test.go index 913847b..7428dc7 100644 --- a/stream/stream_example_test.go +++ b/stream/stream_example_test.go @@ -412,3 +412,22 @@ func ExampleStream_LastIndexOf() { // -1 // 3 } + +func ExampleStream_ToMap() { + type Person struct { + Name string + Age int + } + s := FromSlice([]Person{ + {Name: "Tom", Age: 10}, + {Name: "Jim", Age: 20}, + {Name: "Mike", Age: 30}, + }) + m := ToMap(s, func(p Person) (string, Person) { + return p.Name, p + }) + fmt.Println(m) + + // Output: + // map[Jim:{Jim 20} Mike:{Mike 30} Tom:{Tom 10}] +} diff --git a/stream/stream_test.go b/stream/stream_test.go index 5b91790..cf6e0a2 100644 --- a/stream/stream_test.go +++ b/stream/stream_test.go @@ -400,3 +400,26 @@ func TestStream_LastIndexOf(t *testing.T) { assert.Equal(-1, s.LastIndexOf(0, func(a, b int) bool { return a == b })) assert.Equal(4, s.LastIndexOf(2, func(a, b int) bool { return a == b })) } + +func TestStream_ToMap(t *testing.T) { + assert := internal.NewAssert(t, "TestStream_ToMap") + type Person struct { + Name string + Age int + } + s := FromSlice([]Person{ + {Name: "Tom", Age: 10}, + {Name: "Jim", Age: 20}, + {Name: "Mike", Age: 30}, + }) + m := ToMap(s, func(p Person) (string, Person) { + return p.Name, p + }) + expected := map[string]Person{ + "Tom": {Name: "Tom", Age: 10}, + "Jim": {Name: "Jim", Age: 20}, + "Mike": {Name: "Mike", Age: 30}, + } + assert.EqualValues(expected, m) + +}