Home > Blockchain >  Removing sequential repeating items from List in Kotlin?
Removing sequential repeating items from List in Kotlin?

Time:02-11

I'm looking for a way in Kotlin to prevent repeating items in a list but still preserve the order. For example

1, 2, 3, 4, 4, 4, 1, 1, 2, 3, 4, 4 

should become

1, 2, 3, 4, 1, 2, 3, 4

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?

CodePudding user response:

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
}

CodePudding user response:

You can do it by using Kotlin Flows

viewModelScope.launch {
        list.asFlow()
            .distinctUntilChanged()
            .collect {
                Log.d(TAG, "distict numbers: $it")
            }
    }
  • Related