What is the easiest way to determine if `list` con...
# announcements
i
What is the easiest way to determine if
list
contains items with the same value (we don’t know what value it may be). Is there any operator or combination fo operators to achieve this ? eg `
Copy code
listOf("A", "A", "A")  //true
listOf("A", "A", "B")  //false
`
👍 1
e
.all {}
2
👍 1
a
I understand he wants something like
.toSet().size == 1
2
👍 3
👍🏻 1
i
Exactly @arekolek. Thanks
r
I always have problems building entirely new collections just to check something. My algorithmics teacher would cry seeing this
a
If you prefer to avoid creating the intermediary set, you could do for example
.asSequence().zipWithNext().all { (a, b) -> a == b }
r
Still creating a lot of stuff there, aren’t you?
I would create and extension that does a simple while loop
a
Only a
Sequence
object that uses the iterator
r
It’s probably irrelevant with nowadays available power anyway, so I guess you should use the solution which is the shortest to both write and understand
@arekolek
.all
does stuff too
a
it iterates the
Sequence
, doesn’t create any objects
r
The lambda itself is one
a
inlined though
r
I meant that the lambda compiled as a whole new class, and you’d use an instance of that class there
I would create an extension function with a clear name which does a simple loop. Shorter than the sequence solution to write and understand and faster to understand than the set solution.
e
But why would you do it, if
all
already does all the work 🤔
a
I guess you could do it with just
all
like this
all { first() == it }
, is that what you mean?
👍 2
i
distinct
may be also an option
listOf(1, 1, 1).distinct().size == 1 //true
e
Oh, I just noticed that you don't know what value is inside the collection. I'm sorry, yes,
all
doesn't help
a
I mean it kind of does,
.run { all { first() == it } }
makes more sense to me than the set or sequence ones
e
Well, actually, you're right. For some weird reason I though that comparing each element to the first one is undeterministic
d
Just bear in mind that
all
over an empty collection is always
true
, no matter what the passed predicate is (i.e. behaviour is different from the `toSet`/`distinct` approach) See this demo: https://pl.kotl.in/r12sFGv2X
i
Great tip @dsavvinov