Example usage for java.util Collection iterator

List of usage examples for java.util Collection iterator

Introduction

In this page you can find the example usage for java.util Collection iterator.

Prototype

Iterator<E> iterator();

Source Link

Document

Returns an iterator over the elements in this collection.

Usage

From source file:Main.java

public static <T> T getSole(Collection<T> l) {
    return l.size() == 1 ? l.iterator().next() : null;
}

From source file:Main.java

public static <T> T nullSafeFirstElement(Collection<T> collection) {
    try {/*from  w w w . j a  v a 2 s .com*/
        return collection.iterator().next();
    } catch (Exception e) {
        return null;
    }
}

From source file:Main.java

public static <T> T first(Collection<T> collection) {
    Iterator<T> iterator = collection.iterator();
    return iterator.hasNext() ? iterator.next() : null;
}

From source file:Main.java

/**
 * Modifies and returns the collection./*from w  w  w.  jav  a 2 s .  co  m*/
 */
public static Collection filterByClass(Collection collection, Class c) {
    for (Iterator i = collection.iterator(); i.hasNext();) {
        Object item = i.next();
        if (!c.isInstance(item)) {
            i.remove();
        }
    }

    return collection;
}

From source file:Main.java

public static <E> E getFirst(Collection<E> collection, E defaultValue) {
    Iterator<E> iterator = collection.iterator();
    return iterator.hasNext() ? iterator.next() : defaultValue;
}

From source file:Main.java

public static <T> T getFirstNonNull(Collection<T> c) {
    T ret = null;/*from w  w  w  . ja  v  a 2s  .  c o m*/
    Iterator<T> it = c.iterator();
    while (it.hasNext() && ret == null) {
        T t = it.next();
        if (t != null)
            ret = t;
    }
    return ret;
}

From source file:Main.java

public static <T> T first(Collection<T> list) {
    Iterator<T> iterator = list.iterator();
    if (iterator.hasNext()) {
        return iterator.next();
    }/*from  www.  j  a v a 2s  . co  m*/
    return null;
}

From source file:Main.java

public static <O> List<O> head(Collection<O> c, int num) {
    return extract(c != null ? c.iterator() : null, num);
}

From source file:Main.java

private static String toString(Collection message) {
    Iterator it = message.iterator();
    if (!it.hasNext())
        return "[]";

    StringBuilder sb = new StringBuilder();
    sb.append('[');
    for (;;) {/*from ww w.  j  a v a 2 s . c o m*/
        Object e = it.next();
        sb.append(e);
        if (!it.hasNext())
            return sb.append(']').toString();
        sb.append(',').append('\n').append(' ');
    }
}

From source file:Main.java

/**
 *
 * @param <T>/*from   ww  w .j  a v  a  2 s .c  o m*/
 * @param collection
 * @return first element or null if empty
 */
public static <T> T getFirstElement(Collection<? extends T> collection) {
    return collection.size() > 0 ? collection.iterator().next() : null;
}