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)
| 306 | * elements. The state of the iterator is unspecified. |
| 307 | */ |
| 308 | @CanIgnoreReturnValue // TODO(kak): Consider removing this? |
| 309 | public static <T> T getOnlyElement(Iterator<T> iterator) { |
| 310 | T first = iterator.next(); |
| 311 | if (!iterator.hasNext()) { |
| 312 | return first; |
| 313 | } |
| 314 | |
| 315 | StringBuilder sb = new StringBuilder(); |
| 316 | sb.append("expected one element but was: <" + first); |
| 317 | for (int i = 0; i < 4 && iterator.hasNext(); i++) { |
| 318 | sb.append(", " + iterator.next()); |
| 319 | } |
| 320 | if (iterator.hasNext()) { |
| 321 | sb.append(", ..."); |
| 322 | } |
| 323 | sb.append('>'); |
| 324 | |
| 325 | throw new IllegalArgumentException(sb.toString()); |
| 326 | } |
| 327 | |
| 328 | /** |
| 329 | * Returns the single element contained in {@code iterator}, or {@code |
no test coverage detected