MCPcopy
hub / github.com/google/guava / getOnlyElement

Method getOnlyElement

guava/src/com/google/common/collect/Iterators.java:310–327  ·  view source on GitHub ↗

Returns the single element contained in {@code iterator}. @throws NoSuchElementException if the iterator is empty @throws IllegalArgumentException if the iterator contains multiple elements. The state of the iterator is unspecified.

(Iterator<T> iterator)

Source from the content-addressed store, hash-verified

308 * iterator is unspecified.
309 */
310 @ParametricNullness
311 public static <T extends @Nullable Object> T getOnlyElement(Iterator<T> iterator) {
312 T first = iterator.next();
313 if (!iterator.hasNext()) {
314 return first;
315 }
316
317 StringBuilder sb = new StringBuilder().append("expected one element but was: <").append(first);
318 for (int i = 0; i < 4 && iterator.hasNext(); i++) {
319 sb.append(", ").append(iterator.next());
320 }
321 if (iterator.hasNext()) {
322 sb.append(", ...");
323 }
324 sb.append('>');
325
326 throw new IllegalArgumentException(sb.toString());
327 }
328
329 /**
330 * Returns the single element contained in {@code iterator}, or {@code defaultValue} if the

Callers 2

getOnlyElementMethod · 0.95

Calls 4

nextMethod · 0.65
toStringMethod · 0.65
hasNextMethod · 0.45
appendMethod · 0.45