Java Iterable Size getSingleOrNull(Iterable iterable)

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

Description

Get a single element from iterable.

License

Apache License

Parameter

Parameter Description
iterable to find a single element.
T type of the element.

Exception

Parameter Description
IllegalStateException in case the iterable contains more than 1 element.

Return

the element iff there is exactly one, null iff there is 0.

Declaration

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

Method Source Code

//package com.java2s;
/*/*from w  w w . java  2s  .  c  o m*/
 * Copyright (c)  [2011-2016] "Pivotal Software, Inc." / "Neo Technology" / "Graph Aware Ltd."
 *
 * This product is licensed to you under the Apache License, Version 2.0 (the "License").
 * You may not use this product except in compliance with the License.
 *
 * This product may include a number of subcomponents with
 * separate copyright notices and license terms. Your use of the source
 * code for these subcomponents is subject to the terms and
 * conditions of the subcomponent's license, as noted in the LICENSE file.
 *
 */

import java.util.Iterator;

public class Main {
    /**
     * Get a single element from iterator.
     *
     * @param iterator to find a single element.
     * @param <T>      type of the element.
     * @return the element iff there is exactly one, null iff there is 0.
     * @throws IllegalStateException in case the iterable contains more than 1 element.
     */
    public static <T> T getSingleOrNull(Iterator<T> iterator) {
        T result = null;

        if (iterator.hasNext()) {
            result = iterator.next();
        }

        if (iterator.hasNext()) {
            throw new IllegalStateException("Iterable has more than one element, which is unexpected");
        }

        return result;
    }

    /**
     * Get a single element from iterable.
     *
     * @param iterable to find a single element.
     * @param <T>      type of the element.
     * @return the element iff there is exactly one, null iff there is 0.
     * @throws IllegalStateException in case the iterable contains more than 1 element.
     */
    public static <T> T getSingleOrNull(Iterable<T> iterable) {
        return getSingleOrNull(iterable.iterator());
    }
}

Related

  1. countElements(Iterable pairs)
  2. getIterableSize(Iterable iterable)
  3. getSingle(Iterable it)
  4. getSingleElementOrNull(Iterable coll)
  5. getSingleIfExist(Iterable iterable)
  6. iterableSize(Iterable iterable)
  7. iterableSize(Iterable itrbl)
  8. iterableSizeEq(Iterable itrbl, int k)
  9. singleOrNull(Iterable iterable)