Remove object from ArrayList with some Object property
Solution 1
Using Java-8 Collection#removeIf
myList.removeIf(obj -> obj.id == 10);
With Java-7 you'll have to use iterator:
for(Iterator<MyType> iterator = myList.iterator(); iterator.hasNext(); ) {
if(iterator.next().id == 10)
iterator.remove();
}
Note that list iteration is necessary in any case. In Java-8 removeIf
method it's just performed internally.
Solution 2
It is not possible1 to remove instances of an element from an ArrayList
without iterating the list in some way2. The ArrayList
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.
Solution 3
If you really do not want to iterate over the list, you could use a stream but I personnally prefer Collection#removeIf
like @TagirValeev suggested
myList = myList.stream()
.filter(x -> x.id() != 10)
.collect(Collectors.toList());
django
Updated on July 09, 2022Comments
-
django almost 2 years
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? -
django about 8 years@Tagir Valeev Thanks a lot for ur valid reply.Is there any way without Iterate???
-
Yassin Hajaj about 8 years@django Check the Java-8 possibility.
-
pvg about 8 yearsBoth of these involve iterating over the list.
-
django about 8 years@Tagir Valeev ..Ya It is working. One more doubt Istead of remove I need to get that object with id=10. what shud I do?