Java Utililty Methods Collection First

List of utility methods to do Collection First

Description

The list of methods to do Collection First are organized into topic(s).

Method

TgetFirstItem(Collection collection)
Get the 1st element of the collection.
if (isEmpty(collection)) {
    return null;
for (T item : collection) {
    return item;
return null;
XgetFirstItem(Collection c)
Returns the first item in the collection or null if the collection is empty
X o;
if (c == null || c.isEmpty()) {
    o = null;
} else if (c instanceof List) {
    o = ((List<X>) c).get(0);
} else {
    o = c.iterator().next();
return o;
TgetFirstItemInCollection(Collection collection)
get First Item In Collection
for (T item : collection) {
    return item;
return null;
ListgetFirstN(Collection objects, int n)
get First N
if (objects == null)
    return null;
List<E> newlist = new ArrayList<E>();
int i = 0;
for (E item : objects) {
    if (i < n)
        newlist.add(item);
    else
...
TgetFirstNonNull(Collection c)
get First Non Null
T ret = null;
Iterator<T> it = c.iterator();
while (it.hasNext() && ret == null) {
    T t = it.next();
    if (t != null)
        ret = t;
return ret;
...
TgetFirstNotNullValue(final Collection collection)
Returns the first not null element if the collection is not null and have not null value, else return null.
if (isNotEmpty(collection)) {
    for (T element : collection) {
        if (element != null) {
            return element;
return null;
...
TgetFirstOrNull(final Collection collection)
Return either the first element when the collection is not null and empty or null.
if (isEmpty(collection)) {
    return null;
if (collection instanceof List) {
    return ((List<T>) collection).get(0);
} else {
    return collection.iterator().next();
TgetFirstSortedItem(Collection items, T defaultValue)
get First Sorted Item
List<T> sortedItems = new ArrayList<T>(items);
Collections.sort(sortedItems);
for (T item : sortedItems)
    return item;
return defaultValue;
intgetUnionSize(Collection firstCollection, Collection secondCollection)
Given two Collections, return the size of their union
int firstSize = (firstCollection != null) ? firstCollection.size() : 0;
int secondSize = (secondCollection != null) ? secondCollection.size() : 0;
if (firstSize == 0)
    return secondSize;
if (secondSize == 0)
    return firstSize;
int size;
Collection<? extends E> iteratingCollection;
...
Collectionintersect(Collection firstSet, Collection secondSet)
intersect
ArrayList result = new ArrayList();
Iterator it = firstSet.iterator();
while (it.hasNext()) {
    Object oj = it.next();
    if (secondSet.contains(oj)) {
        result.add(oj);
return result;