How to remove element from ArrayList by checking its value?
You would need to use an Iterator like so:
Iterator<String> iterator = a.iterator();
while(iterator.hasNext())
{
String value = iterator.next();
if ("abcd".equals(value))
{
iterator.remove();
break;
}
}
That being said, you can use the remove(int index) or remove(Object obj) which are provided by the ArrayList class. Note however, that calling these methods while you are iterating over the loop, will cause a ConcurrentModificationException, so this will not work:
for(String str : a)
{
if (str.equals("acbd")
{
a.remove("abcd");
break;
}
}
But this will (since you are not iterating over the contents of the loop):
a.remove("acbd");
If you have more complex objects you would need to override the equals method.
One-liner (java8):
list.removeIf(s -> s.equals("acbd")); // removes all instances, not just the 1st one
(does all the iterating implicitly)
for java8 we can simply use removeIf function like this
listValues.removeIf(value -> value.type == "Deleted");
In your case, there's no need to iterate through the list, because you know which object to delete. You have several options. First you can remove the object by index (so if you know, that the object is the second list element):
a.remove(1); // indexes are zero-based
Or, you can remove the first occurence of your string:
a.remove("acbd"); // removes the first String object that is equal to the
// String represented by this literal
Or, remove all strings with a certain value:
while(a.remove("acbd")) {}
It's a bit more complicated, if you have more complex objects in your collection and want to remove instances, that have a certain property. So that you can't remove them by using remove
with an object that is equal to the one you want to delete.
In those case, I usually use a second list to collect all instances that I want to delete and remove them in a second pass:
List<MyBean> deleteCandidates = new ArrayList<>();
List<MyBean> myBeans = getThemFromSomewhere();
// Pass 1 - collect delete candidates
for (MyBean myBean : myBeans) {
if (shallBeDeleted(myBean)) {
deleteCandidates.add(myBean);
}
}
// Pass 2 - delete
for (MyBean deleteCandidate : deleteCandidates) {
myBeans.remove(deleteCandidate);
}