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?
Asked
Active
Viewed 265 times
0
-
I think you can override the hash code(It's my Preference) for CustomObject and then you can use remove(customObject) method of List. – Rajnish suryavanshi Nov 04 '19 at 09:04
-
1https://stackoverflow.com/a/57356695/7666442 – AskNilesh Nov 04 '19 at 09:10
-
use this code --> list.remove(new Custom()); – Thoriya Prahalad Nov 04 '19 at 09:12
-
Does this answer your question? [How to remove some items from an arraylist without loop and less time complexity?](https://stackoverflow.com/questions/57356584/how-to-remove-some-items-from-an-arraylist-without-loop-and-less-time-complexity) – Manoj Perumarath Nov 04 '19 at 10:04
-
@ManojPerumarath no – Parth Anjaria Nov 04 '19 at 10:09
2 Answers
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