Java Iterable unique(Iterable source, T defaultElement)

Here you can find the source of unique(Iterable source, T defaultElement)

Description

Gets either the only element or the default one.

License

Open Source License

Declaration

public static <T> T unique(Iterable<T> source, T defaultElement) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.Iterator;

public class Main {
    /**/*w  ww  .  j  a v  a  2 s.c o  m*/
     * Gets either the only element or the default one. If there are multiple elements in <tt>source</tt>, an
     * {@link IllegalStateException} is thrown.
     */
    public static <T> T unique(Iterable<T> source, T defaultElement) {
        T element = defaultElement;

        if (source != null) {
            Iterator<T> i = source.iterator();

            if (i.hasNext()) {
                element = i.next();

                if (i.hasNext()) {
                    throw new IllegalStateException("Element not unique!");
                }
            }
        }

        return element;
    }
}

Related

  1. removeIgnoreCase(Iterable haystack, String needle)
  2. secondOf(final Iterable iterable)
  3. sequenceEqual(Iterable one, Iterable two)
  4. shallowCopy(Iterable ori)
  5. toFriendlyString(Iterable iterable, String seperator)
  6. valueOfMultiple(Iterable... iterables)