Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

229
Vistas
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?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You can do it by using Kotlin Flows

viewModelScope.launch {
        list.asFlow()
            .distinctUntilChanged()
            .collect {
                Log.d(TAG, "distict numbers: $it")
            }
    }
over 4 years ago · Santiago Trujillo Denunciar

0

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
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda