Abhishek Kanth
Abhishek Kanth

Reputation: 107

how to remove blank items from ArrayList.Without removing index wise

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

Answers (4)

Alexis C.
Alexis C.

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

Devolus
Devolus

Reputation: 22084

You can remove an object by value.

while(al.remove(""));

Upvotes: 1

AlexR
AlexR

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

darijan
darijan

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

Related Questions