Skip to content

Instantly share code, notes, and snippets.

@rgrig
Created July 3, 2014 07:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rgrig/95e4efee13ddb360ad58 to your computer and use it in GitHub Desktop.
Save rgrig/95e4efee13ddb360ad58 to your computer and use it in GitHub Desktop.
getOnlyElement
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class A {
public static <T> T getOnlyElement(Iterable<T> xs, Optional<T> e, Optional<T> xx) {
Iterator<T> i = xs.iterator();
if (!i.hasNext()) {
if (e.isPresent()) return e.get();
throw new NoSuchElementException();
}
T r = i.next();
if (i.hasNext()) {
if (xx.isPresent()) return xx.get();
throw new IllegalArgumentException();
}
return r;
}
public static <T> T getOnlyElement(Iterable<T> xs) {
return getOnlyElement(xs, Optional.<T>absent(), Optional.<T>absent());
}
public static <T> T getOnlyElement(Iterable<T> xs, T d) {
return getOnlyElement(xs, Optional.of(d), Optional.<T>absent());
}
public static <T> T getOnlyElement(Iterable<T> xs, T d1, T d2) {
return getOnlyElement(xs, Optional.of(d1), Optional.of(d2));
}
public static String describe(Iterable<String> xs) {
return getOnlyElement(xs, "none", "all");
}
public static void main(String[] args) {
System.out.printf("processing %s%n", describe(Lists.newArrayList(args)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment