Reputation: 107
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]
Upvotes: 10
Views: 30205
Reputation: 93842
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]
Upvotes: 37
Reputation: 115328
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.
Upvotes: 0
Reputation: 9775
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("");
}
Upvotes: 1