I have ArrayList, from which I want to remove an element which has particular value...
for eg.
ArrayList a=new ArrayList
One-liner (java8):
list.removeIf(s -> s.equals("acbd")); // removes all instances, not just the 1st one
(does all the iterating implicitly)
use contains() method which is available in list interface to check the value exists in list or not.If it contains that element, get its index and remove it
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.
You should check API for these questions.
You can use remove methods.
a.remove(1);
OR
a.remove("acbd");
Use a iterator to loop through list and then delete the required object.
Iterator itr = a.iterator();
while(itr.hasNext()){
if(itr.next().equals("acbd"))
itr.remove();
}