集册 Java实例教程 获取Iterable中的唯一元素或默认元素。

获取Iterable中的唯一元素或默认元素。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

362
获取Iterable中的唯一元素或默认元素。


//package com.nowjava;

import java.util.Iterator;/*from nowjava - 时代Java*/


public class Main {

    /**

     * 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(
展开阅读全文