Java tutorial
//package com.java2s; //it under the terms of the GNU Affero General Public License as published by import java.util.Iterator; public class Main { public static <T> T getSingleIfExist(Iterable<T> iterable) { if (iterable == null) return null; final Iterator<? extends T> iter = iterable.iterator(); if (!iter.hasNext()) return null; final T result = iter.next(); if (iter.hasNext()) { throw new IllegalArgumentException("More than (expected) one element in " + iterable); } return result; } }