Created
July 3, 2014 07:45
-
-
Save rgrig/95e4efee13ddb360ad58 to your computer and use it in GitHub Desktop.
getOnlyElement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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