0

I have a list of CustomObject and I wish to remove a value from the list with same id(property of CustomObject). Now this can be done by using loop. But that seems a very unnecessary and inefficient code to me. Is there any other way to get specific object with id?

Parth Anjaria
  • 3,961
  • 3
  • 30
  • 62

2 Answers2

0

If your project's min sdk version is 24 and up then you can use removeIf

yourList.removeIf(model -> model.id == yourid);

If you check the code inside removeIf, actually it also iterate throughout the list to remove matching object.

Beside this, if you are using Kotlin or want to, Then you can filter the list with your id and then remove those from your list.

val yourList = arrayListOf<Model>()

val removeList = yourList.filter { model ->
    model.id == yourid
}

yourList.removeAll(removeList)
Md. Asaduzzaman
  • 14,963
  • 2
  • 34
  • 46
0

If you don't want to use the removeIf method, you can do something like this:

yourList.apply { removeAt( first { it.id == id } ) }
r2rek
  • 2,083
  • 13
  • 16