Reputation:
Here is my code for arrayList ,
String[] n = new String[]{"google","microsoft","apple"};
final List<String> list = new ArrayList<String>();
Collections.addAll(list, n);
how to remove all the elements that containsle
from the above list.
Is there any default method or by looping we have to remove manually.tell me how to do it.Thanks.
Upvotes: 1
Views: 5906
Reputation: 713
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);
}
}
Upvotes: 2
Reputation: 6276
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]);
}
Upvotes: 0
Reputation: 121998
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.
Upvotes: 0
Reputation: 31
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.
Upvotes: 0