Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

237
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!