### Question:
OptionalCollectors { public static <T> Collector<T, ?, Optional<T>> toOptional() { return toOptional(Optional::empty, Optional::of); } private  OptionalCollectors(); static Collector<T, ?, Optional<T>> toOptional(); static Collector<Integer, ?, OptionalInt> toOptionalInt(); static Collector<Long, ?, OptionalLong> toOptionalLong(); static Collector<Double, ?, OptionalDouble> toOptionalDouble(); static Collector<T, ?, O> toOptional(Supplier<O> empty,
                                                     Function<T, O> factory);  }### Answer:
@Test public void toOptional() { Collector<String, ?, Optional<String>> collector = OptionalCollectors.toOptional(); assertThat(Stream.<String>empty().collect(collector)).isEmpty(); assertThat(Stream.of((String) null).collect(collector)).isEmpty(); assertThat(Stream.of("foo").collect(collector)).hasValue("foo"); assertThatThrownBy( () -> Stream.of("foo", "bar").collect(collector)) .isInstanceOf(IllegalStateException.class) .hasMessage("Multiple values for optional: ['foo', 'bar', ...]"); assertThatThrownBy( () -> Stream.of("foo", null).collect(collector)) .isInstanceOf(IllegalStateException.class) .hasMessage("Multiple values for optional: ['foo', null, ...]"); assertThatThrownBy( () -> Stream.of(null, "bar").collect(collector)) .isInstanceOf(IllegalStateException.class) .hasMessage("Multiple values for optional: [null, 'bar', ...]"); }