Returns the single element contained in 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)
| 318 | */ |
| 319 | |
| 320 | @CanIgnoreReturnValue // TODO(kak): Consider removing this? |
| 321 | public static <T> T getOnlyElement(Iterator<T> iterator) { |
| 322 | T first = iterator.next(); |
| 323 | if (!iterator.hasNext()) { |
| 324 | return first; |
| 325 | } |
| 326 | StringBuilder sb = new StringBuilder(); |
| 327 | sb.append("expected one element but was: <" + first); |
| 328 | for (int i = 0; i < 4 && iterator.hasNext(); i++) { |
| 329 | sb.append(", " + iterator.next()); |
| 330 | } |
| 331 | if (iterator.hasNext()) { |
| 332 | sb.append(", ..."); |
| 333 | } |
| 334 | |
| 335 | sb.append('>'); |
| 336 | throw new IllegalArgumentException(sb.toString()); |
| 337 | } |
| 338 | |
| 339 | /** |
| 340 | * Returns the single element contained in {@code iterator}, or {@code |
no test coverage detected