Checks to see if the collection is of size 1 and if so returns that element. - Java java.util

Java examples for java.util:Collection Element

Description

Checks to see if the collection is of size 1 and if so returns that element.

Demo Code


//package com.java2s;

import java.util.Collection;

public class Main {
    public static void main(String[] argv) {
        Collection collection = java.util.Arrays.asList("asdf",
                "java2s.com");
        System.out.println(firstOnly(collection));
    }/*www  .  j a  va  2 s .c o  m*/

    /**
     * Checks to see if the collection is of size 1 and if so returns that element.
     * <p>
     * This method is particularly nice for DAO implementations, as all get methods should return a collection of
     * objects rather than just one object. This enables the DAO to return several objects in case the query is wrong,
     * or worse, if there are data problems in the database. Hence avoid code such as
     * 
     * <pre>
     * class PersonDao {
     *    Person getPerson(String arg1, String arg2);
     * }
     * </pre>
     * 
     * instead use
     * 
     * <pre>
     * class PersonDao {
     *    Collection&lt;Person&gt; getPerson(String arg1, String arg2);
     * }
     * </pre>
     * 
     * and query the first element with this method
     * 
     * @param collection
     *            any non-collection
     * @return first element of a collection, if the collection has a size of 1.
     * @throws IllegalStateException
     *             when collection is not of size 1
     * @since 0.3
     */
    public static <T> T firstOnly(final Collection<T> collection) {
        if (collection == null)
            throw new IllegalArgumentException(
                    "argument collection is null");
        if (collection.size() != 1)
            throw new IllegalStateException("Collection has size "
                    + collection.size() + " must have size 1!");
        return collection.iterator().next();
    }
}

Related Tutorials