code: public static <E> Collector<E, ?, Optional<E>> getOnly() {
      return Collector.of(
          AtomicReference<E>::new,
          (ref, e) -> {
            if (!ref.compareAndSet(null, e)) {
              throw new IllegalArgumentException("Multiple values");
            }
          },
          (ref1, ref2) -> {
            if (ref1.get() == null) {
              return ref2;
            } else if (ref2.get() != null) {
              throw new IllegalArgumentException("Multiple values");
            } else {
              return ref1;
            }
          },
          ref -> Optional.ofNullable(ref.get()),
          Collector.Characteristics.UNORDERED);
    }
docs: Can be replaced with MoreCollectors.onlyElement as soon as we can upgrade to the newest Guava
  version.
  
  @param <E> type of the element.
  @return only one element.
  @see <a href="https://stackoverflow.com/questions/22694884/filter-java-stream-to-1-and-only-1-element"/>