is there a way to compare elements to each other i...
# getting-started
h
is there a way to compare elements to each other in a list? For example if I have:
Copy code
listOf(A, B, C)
I want a way to compare A to B, B to C and A to C so they are all evaluated against each other
1
s
Copy code
val list = listOf("a", "b", "c")
    list.forEach { fst -> list.forEach { snd -> println("$fst,$snd") } }
1
s
What exactly do you want to have as a return value? If you want to check if all values are equal you could just compare them to the first value for example..
Copy code
val list = listOf(A, B, C)
val isEqual = list.all { it == list.first() }
But I doubt this is what you are looking for, could you give me an example of what you expect?
👆 1
j
Comparing against the 1st element is a good solution if you want to make sure everything is equal. If you want to check whether elements next to each other are equal, consider using zipWithNext():
Copy code
val list = listOf(A, B, C)
(list + list.first()).zipWithNext().map { (a, b) -> a == b }
This matches the original request, but if you have 4 elements you will only get 4 comparisons, not the cross product (e.g. A==C and B==D would never run)
v
.distinct().size == 1?
👀 3
h
I was able to do what I wanted with this
Copy code
val elementsToDrop = myList.indexOf(zone)
val subsequence = myList.drop(elementsToDrop + 1)
if (subsequence.isEmpty()) return@map true
....