Java tutorial
//package com.java2s; import java.util.*; public class Main { public static <T> T checkAndReturnOnlyElement(Collection<T> collection) { if (collection == null || collection.size() == 0) { return null; } else if (collection.size() != 1) { throw new IllegalStateException("collection size is " + collection.size()); } return collection.iterator().next(); } }