Thursday, June 05, 2008

Removing null or specific values from list in Java

Have you tried to remove null values from a List (may a ArrayList). Yesterday I was trying it out, when I had to remove null values from a List before processing it.

Initially, I was trying with the simple for loop and out I was getting Still NullPointerException while processing. I tried with couple of ways, before I came to a efficient one. Lets see this with an example:

Lets see what are the flaws, when u try to remove null values from a List with a for loop:

List li = new ArrayList();

FileListItem fLI = new FileListItem();

fLI.setFormFileName("123");

FileListItem fLI2 = new FileListItem();

FileListItem fLI3 = new FileListItem();

FileListItem fLI4 = new FileListItem();

fLI4.setFormFileName("456");

li.add(fLI);

li.add(fLI2);

li.add(fLI3);

li.add(fLI4);

System.out.println("====this.fileList() =====" + li);

for(int i = 0;i <>

System.out.println("li Size ====" + li.size() + " & Value of i ===== "+i);

FileListItem fileListItem = (FileListItem) li.get(i);

System.out.println("fileListItem is ====== "+fileListItem);

if(null == fileListItem.getFormFileName())

li.remove(i);

}

System.out.println("====this.fileList() =====" + li);

What output it will produce, Lets see

=== this.fileList()==[FileListItem{ formFileName=123}, FileListItem{ formFileName=null}, FileListItem{ formFileName=null}, FileListItem{ formFileName=456}]

li Size ====4 & Value of i ===== 0

fileListItem is ====== FileListItem{ formFileName=123}

li Size ====4 & Value of i ===== 1

fileListItem is ====== FileListItem{ formFileName=null}

li Size ====3 & Value of i ===== 2

fileListItem is ====== FileListItem{ formFileName=456}

=== this.fileList()== [FileListItem{ formFileName=123}, FileListItem{ formFileName=null}, FileListItem{ formFileName=456}]

Here it still contains a Null Value in it.

So what is the efficient way to remove elements from a list:

Iterator is wonderful thing to handle it. Lets see the same thing with Iterator.

System.out.println("====this.fileList() =====" + li);

Iterator itr = li.iterator();

while(itr.hasNext()){

FileListItem fileListItem = (FileListItem) itr.next();

if(null == fileListItem.getFormFileName())

itr.remove();

}

System.out.println("====this.fileList() =====" + li);

Here the Output will be :

====this.fileList() ===== [FileListItem{ formFileName=123}, FileListItem{ formFileName=null}, FileListItem{ formFileName=null}, FileListItem{ formFileName=456}]

====this.fileList() ===== [FileListItem{ formFileName=123}, FileListItem{ formFileName=456}]

ListIterator can also be used for the same, but ListIterator give you additional advantage of adding elements to a list, while iterating it.

Please download the complete code from here: ListDemoCode

0 Comments: