### Question:
Collectors { public static <T> Collector<T, ?, Optional<T>> singleOrEmpty() { return java.util.stream.Collectors.reducing( ( left, right ) -> { if( left != null && right != null ) { throw new IllegalArgumentException( "More than one element in stream" ); } if( left != null ) { return left; } return right; } ); } private  Collectors(); static Collector<T, ?, T> single(); static Collector<T, ?, Optional<T>> singleOrEmpty(); static Collector<T, ?, Map<K, U>> toMap(); static Collector<T, ?, M> toMap( Supplier<M> mapSupplier ); static Collector<T, ?, M> toMap( Function<? super T, ? extends K> keyMapper,
                              Function<? super T, ? extends U> valueMapper,
                              Supplier<M> mapSupplier ); static Collector<T, ?, Map<K, U>> toMapWithNullValues(); static Collector<T, ?, M> toMapWithNullValues( Supplier<M> mapSupplier ); static Collector<T, ?, M> toMapWithNullValues( Function<? super T, ? extends K> keyMapper,
                                            Function<? super T, ? extends U> valueMapper,
                                            Supplier<M> mapSupplier );  }### Answer:
@Test public void singleOrEmpty() { assertThat( Stream.of().collect( Collectors.singleOrEmpty() ), equalTo( Optional.empty() ) ); assertThat( Stream.of( 1 ).collect( Collectors.singleOrEmpty() ), equalTo( Optional.of( 1 ) ) ); try { Stream.of( 1, 1 ).collect( Collectors.singleOrEmpty() ); fail( "Should have failed" ); } catch( IllegalArgumentException ex ) {} try { Stream.of( 1, 1, 1 ).collect( Collectors.singleOrEmpty() ); fail( "Should have failed" ); } catch( IllegalArgumentException ex ) {} }
@Test public void singleOrEmpty() { assertEquals( Optional.empty(), Stream.of().collect( Collectors.singleOrEmpty() ) ); assertEquals( Optional.of( 1 ), Stream.of( 1 ).collect( Collectors.singleOrEmpty() ) ); try { Stream.of( 1, 1 ).collect( Collectors.singleOrEmpty() ); fail( "Should have failed" ); } catch( IllegalArgumentException ex ) {} try { Stream.of( 1, 1, 1 ).collect( Collectors.singleOrEmpty() ); fail( "Should have failed" ); } catch( IllegalArgumentException ex ) {} }