Remove items from ArrayList with certain value
There are many ways to tackle this.
- I am using CollectionUtils from apache.common.collection4 or its google equivalent. and then select what you wish using a predicate or in java 8 an lambda expression.
CollectionUtils.select(peeps, new Predicate<Person>() {
@Override
public boolean evaluate(Person object) {
return object.getId().equals("114");
}
});
- use good old iterator and loop over it
Iterator<Person> iterator = peeps.iterator();
while(iterator.hasNext()) {
Person next = iterator.next();
if(next.getId().equals("114")) {
iterator.remove();
}
}
Using Java8:
peeps.removeIf(p -> p.getId().equals("112"));
Note that this is equivalent to linear search and will take O(n)
time. If this operation will be repeated frequently it is recommended to use a HashMap
in order to speed things up to O(1)
.
Alternatively using a sorted list would also do the trick, but require O(log n)
time.
If you are going to be using an ArrayList, the the only way is to go through the entire list, looking at each person, and seeing it their id number is 114. For larger datasets, this is not going to efficient and should be avoided.
If you can change your data structure, then some sort of Map would be better (HashMap is typically a good choice). You could have the id number as a "key" and then associate it with each person. Later you can query the Map by key. The con is you can only have one value as a key, so you can't have say both name and id number keys
Edit:
An more efficient way to do use an ArrayList would be to keep it sorted by id number. Then you can use something like Collections.binarySearch() to quickly access the elements by id number. The con is is that it is expensive to remove from/insert into a sorted array, as everything greater the element has to be moved. So if you are going to be doing relatively few changes compared to the number of reads, this might be viable