StreamUtils { public static <T> Collector<T, List<T>, T> singletonCollector() { return Collector.of(ArrayList::new, List::add, (left, right) -> left, list -> { if (list.isEmpty() || list.size() > 1) { throw new IllegalArgumentException("Expected only one element in the List"); } return list.get(0); } ); }  static Collector<T, List<T>, Optional<T>> singletonOptionalCollector(); static Collector<T, List<T>, T> singletonCollector(); static List<T> iteratorToList(Iterator<T> iterator);  }
@Test public void testSingletonCollector() throws Exception { assertEquals("1", asList("1").stream().collect(singletonCollector())); }
@Test(expected = IllegalArgumentException.class) public void testSingletonCollectorIllegal() throws Exception { new ArrayList<String>().stream().collect(singletonCollector()); }
@Test(expected = IllegalArgumentException.class) public void testSingletonCollectorIllegalMany() throws Exception { Arrays.asList("1", "2").stream().collect(singletonCollector()); }