问题
public class ArrayListTest {
public static void main(String[] args) {
ArrayList al=new ArrayList();
al.add("");
al.add("name");
al.add("");
al.add("");
al.add(4, "asd");
System.out.println(al);
}
}
o/p [, name, , , asd] desire O/p [name,asd]
回答1:
You can use removeAll(Collection<?> c) :
Removes all of this collection's elements that are also contained in the specified collection
al.removeAll(Arrays.asList(null,""));
This will remove all elements that are null
or equals to ""
in your List
.
Output :
[name, asd]
回答2:
You can remove an object by value.
while(al.remove(""));
回答3:
Iterate over the list, read each value, compare it to an empty string ""
and if it is that, remove it:
Iterator it = al.iterator();
while(it.hasNext()) {
//pick up the value
String value= (String)it.next();
//if it's empty string
if ("".equals(value)) {
//call remove on the iterator, it will indeed remove it
it.remove();
}
}
Another option is to call List's remove()
method while there are empty strings in the list:
while(list.contains("")) {
list.remove("");
}
回答4:
List<String> al=new ArrayList<String>();
...................
for(Iterator<String> it = al.iterator(); it.hasNext();) {
String elem = it.next();
if ("".equals(elem)) {
it.remove();
}
}
I do not comment this code. You should study from it yourself. Please pay attention on all details.
来源:https://stackoverflow.com/questions/17131987/how-to-remove-blank-items-from-arraylist-without-removing-index-wise