问题
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.
回答1:
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);
}
}
回答2:
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.
回答3:
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.
回答4:
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]);
}
回答5:
From java 8 You can use
list.removeIf(s -> s.contains("le"));
来源:https://stackoverflow.com/questions/19331422/remove-specific-string-from-arraylist-elements-containing-a-particular-subsrtrin