Skip to main content

Add utility methods to extract a singleton from a Collection or a Map

No replies
doronrajwan
Offline
Joined: 2005-06-30

In some cases, there is a need to extract an element from a map that we know that contains exactly one element.

The only way to do that now is something like:
map.values().iterator().next()

I suggest to add such utility methods to Collections. I give here a sample implementation, but it can be implemented better.

thanks,
Doron.

/**
* @author Doron Rajwan, 2006.
*/
public class Collections {

public T single(Iterator i) {
if (!i.hasNext())
return null;
T obj = i.next();
if (i.hasNext())
throw new RuntimeException("Not a singleton");
return obj;
}

public T single(Collection c) {
return single(c.iterator());
}

public T singleValue(Map<?,T> m) {
return single(m.values().iterator());
}

public T singleKey(Map m) {
return single(m.keySet().iterator());
}
}