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

我们两清 提交于 2019-12-22 04:08:20

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!