Removes nulls from provided collection. - Java java.util

Java examples for java.util:Collection Null Element

Description

Removes nulls from provided collection.

Demo Code


//package com.book2s;

import java.util.Collection;
import java.util.Iterator;

public class Main {
    public static void main(String[] argv) {
        Collection c = java.util.Arrays.asList("asdf", "book2s.com");
        System.out.println(removeNulls(c));
    }/*from   w  w w  .ja  v  a2s . c  om*/

    /**
     * Removes nulls from provided collection.
     * 
     * @param c
     *            to remove nulls from
     * @return number of removed elements
     */
    @SuppressWarnings("rawtypes")
    public static int removeNulls(Collection c) {
        int removed = 0;
        Iterator iterator = c.iterator();
        while (iterator.hasNext()) {
            if (iterator.next() == null) {
                iterator.remove();
                removed++;
            }
        }
        return removed;
    }
}

Related Tutorials