public static <T> Collector<T, ?, Optional<T>> singleton() {
        return Collectors.collectingAndThen(
                Collectors.toList(),
                list -> {
                    if (list.size() > 1) throw new IllegalArgumentException("More than one element");
                    return list.stream().findAny();
                }
        );
    }
Returns a {@code Collector} that returns a singleton, or throws an {@code IllegalArgumentException} if there are more than one item.

@return A collector returning an optional element
@param <T> Type of the input elements.
@throws IllegalArgumentException if there are more than one element
vespajlib/src/main/java/com/yahoo/stream/CustomCollectors.java