Creates new collection that does not contain nulls. - Java java.util

Java examples for java.util:Collection Creation

Description

Creates new collection that does not contain nulls.

Demo Code


//package com.book2s;
import java.util.ArrayList;
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(toCleaned(c));
    }/*  w  w w.  j  a v a 2s . co m*/

    /**
     * Creates new collection that does not contain nulls. Does not change input
     * collection. It is parameterized.
     * 
     * @param c
     *            raw collection to create cleaned collection from.
     * @return collection without nulls
     */
    public static <E> Collection<E> toCleaned(Collection<E> c) {
        ArrayList<E> cleaned = new ArrayList<E>();
        Iterator<E> iterator = c.iterator();
        while (iterator.hasNext()) {
            E e = iterator.next();
            if (e != null) {
                cleaned.add(e);
            }
        }
        return cleaned;
    }
}

Related Tutorials