get First Non Null element from a Collection - Java java.util

Java examples for java.util:Collection Null Element

Description

get First Non Null element from a Collection

Demo Code

// This program is free software: you can redistribute it and/or modify
//package com.java2s;

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

public class Main {
    public static void main(String[] argv) {
        Collection c = java.util.Arrays.asList("asdf", "java2s.com");
        System.out.println(getFirstNonNull(c));
    }//from   www  .  j ava  2 s  .c  om

    public static <T> T getFirstNonNull(Collection<T> c) {
        T ret = null;
        Iterator<T> it = c.iterator();
        while (it.hasNext() && ret == null) {
            T t = it.next();
            if (t != null)
                ret = t;
        }
        return ret;
    }
}

Related Tutorials