10
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]

4 Answers 4

37

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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("");
}

Comments

1

You can remove an object by value.

while(al.remove(""));

2 Comments

yes, but it will remove only first blank space,how to use remove("") method so all blank value from ArrayList will removed?
Use a while loop. When there was something to remove, true is returned. See my update.
0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.