StreamHelper { @SuppressWarnings("unchecked") public static <T, R> Function<T, Stream<R>> instanceOf(Class<R> targetClass) { return item -> targetClass.isInstance(item) ? Stream.of((R) item) : Stream.empty(); }  static BinaryOperator<T> onlyOne(); @SuppressWarnings("unchecked") static Function<T, Stream<R>> instanceOf(Class<R> targetClass);  }
@Test void instanceOf() { List<Object> list = new ArrayList<>(); list.add("text1"); list.add(1); list.add("text2"); list.add(2); List<String> result = list.stream().flatMap(StreamHelper.instanceOf(String.class)).collect(Collectors.toList()); assertEquals(2, result.size()); assertEquals("text1", result.get(0)); assertEquals("text2", result.get(1)); }