'Removing sequential repeating items from List in Kotlin?
I'm looking for a way in Kotlin to prevent repeating items in a list but still preserve the order. For example
val list = listOf(ObjectMock(1,"a"), ObjectMock(2,"c"), ObjectMock(3,"c"),
ObjectMock(4,"a"), ObjectMock(4,"c"), ObjectMock(4,"c"), ObjectMock(1,"a")
, ObjectMock(1,"c"), ObjectMock(2,"c"), ObjectMock(3,"c"), ObjectMock(4,"a")
, ObjectMock(2,"b") )
should become
result = listOf(ObjectMock(1,"a"), ObjectMock(2,"c"), ObjectMock(3,"c"),
ObjectMock(4,"a"), ObjectMock(1,"a") , ObjectMock(2,"c"), ObjectMock(3,"c"), ObjectMock(4,"a")
, ObjectMock(2,"b") )
I'm using a for loop and check next item then add it to different list but Is there a more elegant way to do this?
Solution 1:[1]
this is another way to do it
val list = listOf(1, 2, 3, 4, 4, 4, 1, 1, 2, 3, 4, 4 )
val result = list.fold(emptyList<Int>()){acc, i ->
if (acc.lastOrNull() != i) acc + i else acc
}
Solution 2:[2]
You can do it by using Kotlin Flows
viewModelScope.launch {
list.asFlow()
.distinctUntilChanged()
.collect {
Log.d(TAG, "distict numbers: $it")
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ivo Beckers |
| Solution 2 | Yunis Rasulzade |
