Gets either the only element or the default one in Iterable. - Java Collection Framework

Java examples for Collection Framework:Iterable

Description

Gets either the only element or the default one in Iterable.

Demo Code


//package com.java2s;
import java.util.Iterator;

public class Main {
    /**// w  ww .  ja va2  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 Tutorials