https://kotlinlang.org logo
Title
i

igor.wojda

10/31/2018, 11:09 AM
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 `
listOf("A", "A", "A")  //true
listOf("A", "A", "B")  //false
`
👍 1
e

edwardwongtl

10/31/2018, 11:10 AM
.all {}
2
👍 1
a

arekolek

10/31/2018, 11:11 AM
I understand he wants something like
.toSet().size == 1
2
👍 3
👍🏻 1
i

igor.wojda

10/31/2018, 11:12 AM
Exactly @arekolek. Thanks
r

ribesg

10/31/2018, 11:16 AM
I always have problems building entirely new collections just to check something. My algorithmics teacher would cry seeing this
a

arekolek

10/31/2018, 11:16 AM
If you prefer to avoid creating the intermediary set, you could do for example
.asSequence().zipWithNext().all { (a, b) -> a == b }
r

ribesg

10/31/2018, 11:16 AM
Still creating a lot of stuff there, aren’t you?
I would create and extension that does a simple while loop
a

arekolek

10/31/2018, 11:18 AM
Only a
Sequence
object that uses the iterator
r

ribesg

10/31/2018, 11:18 AM
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

arekolek

10/31/2018, 11:20 AM
it iterates the
Sequence
, doesn’t create any objects
r

ribesg

10/31/2018, 11:20 AM
The lambda itself is one
a

arekolek

10/31/2018, 11:20 AM
inlined though
r

ribesg

10/31/2018, 11:22 AM
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

Egor Trutenko

10/31/2018, 11:25 AM
But why would you do it, if
all
already does all the work 🤔
a

arekolek

10/31/2018, 11:28 AM
I guess you could do it with just
all
like this
all { first() == it }
, is that what you mean?
👍 2
i

igor.wojda

10/31/2018, 11:32 AM
distinct
may be also an option
listOf(1, 1, 1).distinct().size == 1 //true
e

Egor Trutenko

10/31/2018, 11:32 AM
Oh, I just noticed that you don't know what value is inside the collection. I'm sorry, yes,
all
doesn't help
a

arekolek

10/31/2018, 11:33 AM
I mean it kind of does,
.run { all { first() == it } }
makes more sense to me than the set or sequence ones
e

Egor Trutenko

10/31/2018, 11:39 AM
Well, actually, you're right. For some weird reason I though that comparing each element to the first one is undeterministic
d

dsavvinov

10/31/2018, 12:02 PM
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

igor.wojda

10/31/2018, 1:07 PM
Great tip @dsavvinov