Remove object from ArrayList with some Object prop

2020-02-01 05:08发布

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?

4条回答
叛逆
2楼-- · 2020-02-01 05:28

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.

查看更多
可以哭但决不认输i
3楼-- · 2020-02-01 05:32

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());
查看更多
Root(大扎)
4楼-- · 2020-02-01 05:35

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.

查看更多
兄弟一词,经得起流年.
5楼-- · 2020-02-01 05:46

You could not do that without iterator, you should you Hashmap for this.

public class ObjectStructure{
private int Id;
private String name;
//and any data field you need
}

generate all setters and getters.

Use this class in

Hashmap<Integer, ObjectStructure> data = new HashMap<>();

you can add and delete data with only key which is Integer.

data.remove(10);

查看更多
登录 后发表回答