Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

arraylist

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]

like image 432
Abhishek Kanth Avatar asked Jun 16 '13 09:06

Abhishek Kanth


2 Answers

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]
like image 62
Alexis C. Avatar answered Nov 15 '22 20:11

Alexis C.


You can remove an object by value.

while(al.remove(""));
like image 21
Devolus Avatar answered Nov 15 '22 18:11

Devolus