mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-16 18:52:27 +08:00
@@ -420,3 +420,12 @@ func (s Stream[T]) LastIndexOf(target T, equal func(a, b T) bool) int {
|
|||||||
func (s Stream[T]) ToSlice() []T {
|
func (s Stream[T]) ToSlice() []T {
|
||||||
return s.source
|
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 {
|
||||||
|
key, value := mapper(v)
|
||||||
|
result[key] = value
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|||||||
@@ -412,3 +412,22 @@ func ExampleStream_LastIndexOf() {
|
|||||||
// -1
|
// -1
|
||||||
// 3
|
// 3
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ExampleToMap() {
|
||||||
|
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}]
|
||||||
|
}
|
||||||
|
|||||||
@@ -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(-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 }))
|
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)
|
||||||
|
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user