I am maintaining one ArrayList
of objects. And my object structure is Id, name, some other details. I need to remove one the object with some id value say(10) and I don't want to iterate over the list. Is there any solution for this?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
It is not possible1 to remove instances of an element from an
ArrayList
without iterating the list in some way2. TheArrayList
is an array under the hood, and you need to examine each element in the array to see whether it matches the criteria for removal. At the fundamental level, that entails a loop ... to iterate over the elements.Also note that when you remove a single element from an array, all elements with positions after the removed elements need to be moved. On average, that will be half of the array elements.
Now, you can code these operations in ways that avoid you using an explicit
for
loop, but the iteration will be happening behind the scenes, no matter how you code it.1 - Not strictly true. Hypothetically, if you had a separate data structure that (for instance) mapped values to the indexes of elements in the
ArrayList
, then you could remove the elements without iterating. But I can't see how you could manage that data structure efficiently.2 - Iteration doesn't just mean using an
Iterator
. For loops,Stream
,Collections.removeIf
and other solutions all entail iterating the elements of the list under the hood.If you really do not want to iterate over the list, you could use a stream but I personnally prefer
Collection#removeIf
like @TagirValeev suggestedUsing Java-8
Collection#removeIf
With Java-7 you'll have to use iterator:
Note that list iteration is necessary in any case. In Java-8
removeIf
method it's just performed internally.You could not do that without iterator, you should you Hashmap for this.
generate all setters and getters.
Use this class in
you can add and delete data with only key which is Integer.
data.remove(10);