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)
| 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 |