Are you sure you don't want to just start the stream twice? It will be more readable.
But if you want, you can define the consumer of type checking as follows:
public static<T> Consumer<Object> acceptType(Class<T> clazz, Consumer<? super T> cons) { return t -> { if (clazz.isInstance(t)) { cons.accept(clazz.cast(t)); } }; }
Then you can combine multiple users with andThen
:
Consumer<Object> combined = acceptType(Integer.class, i -> ...) .andThen(acceptType(Long.class, lng -> ...))
If you want to hide andThen
, you can define
static<T> Consumer<T> doAll(Consumer<T>... consumers) { return Arrays.stream(consumers) .reduce(Consumer::andThen) .orElse(t -> {}); }
Then he becomes
nums.forEach(doAll( acceptType(Integer.class, i -> ...), acceptType(Long.class, lng -> ..), ... ));
Misha source share