Java tutorial
//package com.java2s; import java.util.Collection; public class Main { public static <T> T single(Collection<T> cl, boolean force) { return single(cl, force, null); } public static <T> T single(Collection<T> cl, boolean force, Object msg) { String amsg = msg == null ? "" : "," + msg.toString(); if (cl.isEmpty()) { if (force) { throw new RuntimeException("force:" + cl + amsg); } else { return null; } } else if (cl.size() > 1) { throw new RuntimeException("tomuch:" + cl + amsg); } else { return cl.iterator().next(); } } }