public static <T> T single(Iterable<T> source) {
Iterator<T> iterator = source.iterator();
if (!iterator.hasNext()) {
throw new IllegalArgumentException("No elements");
}
T first = iterator.next();
if (iterator.hasNext()) {
throw new IllegalArgumentException("More than one element");
}
return first;
}
或者将其放入通用类中,而不是使方法通用。您也可以决定使用不同的异常类型。)
It's a pretty easy one to implement yourself, to be honest:
public static <T> T single(Iterable<T> source) {
Iterator<T> iterator = source.iterator();
if (!iterator.hasNext()) {
throw new IllegalArgumentException("No elements");
}
T first = iterator.next();
if (iterator.hasNext()) {
throw new IllegalArgumentException("More than one element");
}
return first;
}
(Or put it in a generic class instead of making the method generic. You may decide to use a different exception type, too.)
发布评论
评论(4)
老实说,您自己实现它非常容易:(
或者将其放入通用类中,而不是使方法通用。您也可以决定使用不同的异常类型。)
It's a pretty easy one to implement yourself, to be honest:
(Or put it in a generic class instead of making the method generic. You may decide to use a different exception type, too.)
使用番石榴:
Iterables.getOnlyElement (可迭代可迭代)
Using Guava:
Iterables.getOnlyElement(Iterable< T > iterable)
@Jon 解决方案的防御性较低的版本。
添加检查以品味。
A less defensive version of @Jon's solution.
Add checks to taste.
如果您可以使用我的 xpresso 库,您可以编写:
x.list(iterable).toScalar( );
If you can use my xpresso library you can write:
x.list(iterable).toScalar();