diff --git a/stream/stream.go b/stream/stream.go index ddf7ec4..da1a348 100644 --- a/stream/stream.go +++ b/stream/stream.go @@ -373,7 +373,7 @@ func (s Stream[T]) Max(less func(a, b T) bool) (T, bool) { } for i, v := range s.source { - if less(v, max) || i == 0 { + if i == 0 || less(v, max) { max = v } } @@ -391,7 +391,7 @@ func (s Stream[T]) Min(less func(a, b T) bool) (T, bool) { } for i, v := range s.source { - if less(v, min) || i == 0 { + if i == 0 || less(v, min) { min = v } } diff --git a/stream/stream_test.go b/stream/stream_test.go index cf6e0a2..3cedcc4 100644 --- a/stream/stream_test.go +++ b/stream/stream_test.go @@ -423,3 +423,20 @@ func TestStream_ToMap(t *testing.T) { assert.EqualValues(expected, m) } + +func TestStream_MaxMinDoNotCompareWithZeroValue(t *testing.T) { + assert := internal.NewAssert(t, "TestStream_MaxMinDoNotCompareWithZeroValue") + + type Person struct { + Age int + } + s := FromSlice([]*Person{{Age: 20}, {Age: 10}, {Age: 30}}) + + max, ok := s.Max(func(a, b *Person) bool { return a.Age > b.Age }) + assert.Equal(true, ok) + assert.Equal(30, max.Age) + + min, ok := s.Min(func(a, b *Person) bool { return a.Age < b.Age }) + assert.Equal(true, ok) + assert.Equal(10, min.Age) +}