Java Iterable Size singleOrNull(Iterable iterable)

Here you can find the source of singleOrNull(Iterable iterable)

Description

Method returns the single element from an iterable or null if empty iterable is passed.

License

Apache License

Parameter

Parameter Description
iterable any class implementing Iterable<T> interface
T class of iterable element

Exception

Parameter Description
IllegalArgumentException If null is passed as an argument.
IllegalStateException If iterable contains more than one element.

Return

single object of class T or null

Declaration

public static <T> T singleOrNull(Iterable<T> iterable) 

Method Source Code


//package com.java2s;
/*/*ww w.j a  va  2  s  .  c  om*/
 * Copyright (c) 2015 Intel Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.Iterator;

public class Main {
    /**
     * Method returns the single element from an iterable or null if empty iterable is passed.
     *
     * @param iterable  any class implementing Iterable<T> interface
     * @param <T>       class of iterable element
     * @return          single object of class T or null
     *
     * @throws  IllegalArgumentException
     *          If null is passed as an argument.
     *
     * @throws  IllegalStateException
     *          If iterable contains more than one element.
     */
    public static <T> T singleOrNull(Iterable<T> iterable) {
        if (iterable == null) {
            throw new IllegalArgumentException("Null is not a valid argument for this method");
        }
        Iterator<T> iterator = iterable.iterator();
        if (!iterable.iterator().hasNext()) {
            return null;
        } else {
            T element = iterator.next();
            if (iterator.hasNext()) {
                throw new IllegalStateException("Only iterators with 1 or 0 elements are accepted!");
            }
            return element;
        }
    }
}

Related

  1. getSingleOrNull(Iterable iterable)
  2. iterableSize(Iterable iterable)
  3. iterableSize(Iterable itrbl)
  4. iterableSizeEq(Iterable itrbl, int k)
  5. singleOrNull(Iterable iterable)
  6. size(final Iterable iterable)
  7. size(final Iterable iterable)
  8. size(Iterable it)
  9. size(Iterable iterable)