Coding in the small with Google Collections: Iterables.getOnlyElement
Part 2 in a Series.Iterables.getOnlyElement makes sure your collection or iterable contains exactly one element, and returns that. If it contains 0 or 2+ elements, it throws a RuntimeException. This comes up often in unit tests:
Before:
public void testWorkSchedule() {
workSchedule.scheduleUserOnDuty(jesse, mondayAt430pm, mondayAt1130pm);
Set<User> usersOnDuty = workSchedule.getUsersOnDuty(mondayAt800pm);
assertEquals(1, usersOnDuty.size());
assertEquals(jesse, usersOnDuty.iterator().next());
}
After:
public void testWorkSchedule() {
workSchedule.scheduleUserOnDuty(jesse, mondayAt430pm, mondayAt1130pm);
Set<User> usersOnDuty = workSchedule.getUsersOnDuty(mondayAt800pm);
assertEquals(jesse, Iterables.getOnlyElement(usersOnDuty));
}
Iterables.getOnlyElement() describes intent more directly than
Set.iterator().next()
and List.get(0)
. As a special treat, there's an overloaded version to use if your Iterable might be empty.Part 3