StreamHelper { public static <T> BinaryOperator<T> onlyOne() { return (item1, item2) -> { if (item2 != null) throw new IllegalStateException("multiple items found, items=" + item1 + ", " + item2); return item1; }; }  static BinaryOperator<T> onlyOne(); @SuppressWarnings("unchecked") static Function<T, Stream<R>> instanceOf(Class<R> targetClass);  }
@Test void onlyOne() { List<Integer> list = Arrays.asList(1, 2, 3, 4); Optional<Integer> result = list.stream().filter(i -> i > 3).reduce(StreamHelper.onlyOne()); assertEquals((Integer) 4, result.get()); }