Here is my code for arrayList ,
String[] n = new String[]{\"google\",\"microsoft\",\"apple\"};
final List list = new ArrayList
use the following code.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class RemoveElements {
/**
* @param args
*/
public static void main(String[] args) {
String[] n = new String[]{"google","microsoft","apple"};
List<String> list = new ArrayList<String>();
Collections.addAll(list, n);
System.out.println("list"+list);
Iterator<String> iter = list.iterator();
while(iter.hasNext()){
if(iter.next().contains("le"))
iter.remove();
}
System.out.println("list"+list);
}
}
From java 8 You can use
list.removeIf(s -> s.contains("le"));
Why to add
and then remove
?
Check before adding
.
String[] n = new String[]{"google","microsoft","apple"};
final List<String> list = new ArrayList<String>();
for (String string : n) {
if(string.indexOf("le") <0){
list.add(string);
}
}
That add's only one element microsoft
to the list.
Yes, you have to loop from all the values in the list,
This may help you,
String[] array = new String[]{"google","microsoft","apple"};
List<String> finallist = new ArrayList<String>();
for (int i = array.length -1 ; i >= 0 ; i--)
{
if(!array[i].contains("le"))
finallist.add(array[i]);
}
Part of javadoc for List:
/**
* Removes the first occurrence of the specified element from this list,
* if it is present (optional operation). If this list does not contain
* the element, it is unchanged...
boolean remove(Object o);
I hope this is what you are looking for.