Java Collection Size size(final Collection collection)

Here you can find the source of size(final Collection collection)

Description

Determines the size of the given collection, checking for null.

License

Open Source License

Parameter

Parameter Description
collection The collection to get the size of.

Return

The size of the collection. If it is null, zero is returned.

Declaration

public static int size(final Collection<?> collection) 

Method Source Code

//package com.java2s;
/*//from ww w.jav a 2 s. c o m
 * File:                CollectionUtil.java
 * Authors:             Justin Basilico
 * Company:             Sandia National Laboratories
 * Project:             Cognitive Foundry
 *
 * Copyright March 25, 2008, Sandia Corporation.
 * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
 * license for use of this work by or on behalf of the U.S. Government. Export
 * of this program may require a license from the United States Government.
 * See CopyrightHistory.txt for complete details.
 *
 */

import java.util.Collection;

import java.util.Iterator;

public class Main {
    /**
     * Determines the size of the given collection, checking for null.
     *
     * @param collection The collection to get the size of.
     * @return The size of the collection. If it is null, zero is returned.
     */
    public static int size(final Collection<?> collection) {
        if (collection == null) {
            return 0;
        } else {
            return collection.size();
        }
    }

    /**
     * Determines the size of the given iterable. If it is null, zero is
     * returned. If it is a {@code Collection}, then the size method is used.
     * Otherwise, the iterable is iterated over to get the size.
     *
     * @param iterable The iterable to determine the size of.
     * @return The size of the given iterable.
     */
    public static int size(final Iterable<?> iterable) {
        if (iterable == null) {
            // The size is zero.
            return 0;
        } else if (iterable instanceof Collection) {
            // Get the size from the collection. This cast is justified by
            // not having to loop over all the elements.
            return ((Collection<?>) iterable).size();
        } else {
            // Cound up the elements in the iterable.
            int counter = 0;
            final Iterator<?> iterator = iterable.iterator();
            while (iterator.hasNext()) {
                iterator.next();
                counter++;
            }
            return counter;
        }
    }
}

Related

  1. size(Collection col)
  2. size(Collection coll)
  3. size(Collection collection)
  4. size(Collection values)
  5. size(Collection v)
  6. size(final Collection collection)
  7. size(final Collection items)
  8. sizeM1(Collection collection)
  9. sizeOf(Collection collection)