Junior — Middle
How can you select only unique elements in a list?
sobes.tech AI
Answer from AI
In Android (and Java/Kotlin in general), to extract unique elements from a list, you can use a collection type Set, which automatically stores only unique values. For example, if you have a List, you can convert it to a Set, and then back to a List for convenience:
val list = listOf(1, 2, 2, 3, 4, 4, 5)
val uniqueList = list.toSet().toList()
println(uniqueList) // [1, 2, 3, 4, 5]
Also, Kotlin has a function distinct(), which returns a list with unique elements, preserving order:
val uniqueList = list.distinct()
This is the simplest and most efficient way to extract unique elements.