Started as to make a stream splitter to split stream based on condition, but finally found that I did ConsumingRouter, to consume based on condition and while have to provide consumers before using this router not as splited stream can provide consumers then , and use this router inside forEach of stream, please check it and provide me with your feedback and if there is another way to do it:
public class ConsumingRouter<T> implements Consumer<T> {
private Map<Predicate<T>, Consumer<T>> map = new ConcurrentHashMap<>();
public void sub(Predicate<T> p, Consumer<T> c) {
map.put(p, c);
}
@Override
public void accept(T t) {
map.entrySet().forEach(e -> {
if (e.getKey().test(t))
e.getValue().accept(t);
});
}
}
How to use it :
public static void main(String[] args) {
ConsumingRouter<Integer> router = new ConsumingRouter<Integer>();
Predicate<Integer> p1 = (i) -> i % 2 != 0;
Predicate<Integer> p2 = (i) -> i % 2 == 0;
Consumer<Integer> c1 = i -> {
System.out.println(Thread.currentThread().getName() + " Route 1 : "
+ i);
};
Consumer<Integer> c2 = i -> {
System.out.println(Thread.currentThread().getName() + " Route 2 : "
+ i);
};
router.sub(p1, c1);
router.sub(p2, c2);
IntStream.range(0, 1000).boxed().forEach(router);
}