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();
                }
        );
    }
@Test
    public void singleton_collector_throws_when_multiple() {
        List<String> items = List.of("foo1", "bar", "foo2");
        IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
                () -> items.stream().filter(s -> s.startsWith("foo")).collect(CustomCollectors.singleton()));
        assertEquals("More than one element", exception.getMessage());
    }