Java Collection Null getSingleElementOrNull(Collection collection)

Here you can find the source of getSingleElementOrNull(Collection collection)

Description

returns the one and only element of a collection or null if the collection is empty.

License

Open Source License

Exception

Parameter Description
IllegalStateException if the collection has more than one element.

Declaration

public static <E> E getSingleElementOrNull(Collection<E> collection) 

Method Source Code

//package com.java2s;
/***********************************************************************************
 * AlgoTrader Enterprise Trading Framework
 *
 * Copyright (C) 2015 AlgoTrader GmbH - All rights reserved
 *
 * All information contained herein is, and remains the property of AlgoTrader GmbH.
 * The intellectual and technical concepts contained herein are proprietary to
 * AlgoTrader GmbH. Modification, translation, reverse engineering, decompilation,
 * disassembly or reproduction of this material is strictly forbidden unless prior
 * written permission is obtained from AlgoTrader GmbH
 *
 * Fur detailed terms and conditions consult the file LICENSE.txt or contact
 *
 * AlgoTrader GmbH/*ww  w .  j  av a 2 s  . co  m*/
 * Aeschstrasse 6
 * 8834 Schindellegi
 ***********************************************************************************/

import java.util.Collection;

public class Main {
    /**
     * returns the one and only element of a collection or null if the collection is empty.
     * @throws IllegalStateException if the collection has more than one element.
     */
    public static <E> E getSingleElementOrNull(Collection<E> collection) {

        if (collection.isEmpty()) {
            return null;
        } else if (collection.size() > 1) {
            throw new IllegalStateException("collection has more than one elements");
        } else {
            return collection.iterator().next();
        }
    }
}

Related

  1. countNonNull(Collection dist)
  2. countNotNull(Collection collection)
  3. getItemAtPositionOrNull(Collection collection, int position)
  4. getNextNullIndex(C collection)
  5. getNumberOfNonNullElements(final Collection col)
  6. getSizeNullSafe(final Collection collection)
  7. hasAtLeastOneNotNullElement(Collection collection)
  8. hasCollectionNullItem(Collection collection)
  9. isAllNull(Collection values)