fork download
  1. import java.util.function.Consumer;
  2. import java.util.function.Predicate;
  3. import java.util.stream.IntStream;
  4.  
  5. class ConditionalTee<T> implements Predicate<T>, Consumer<T> {
  6.  
  7. private final Predicate<? super T> predicate;
  8. private final Consumer<? super T> consumer;
  9.  
  10. public ConditionalTee(Predicate<? super T> condition, Consumer<? super T> consumer) {
  11. this.predicate = condition;
  12. this.consumer = consumer;
  13. }
  14.  
  15. @Override
  16. public void accept(T t) {
  17. test(t);
  18. }
  19.  
  20. @Override
  21. public boolean test(T t) {
  22. // NOTE: inverted boolean.
  23. // this will be called from a Stream.filter()
  24. // need to return true if the value should stay on the stream
  25. // false if it should be removed from the stream.
  26. // We want to keep it on the stream if we are not siphoning it off
  27. // (return true).
  28. // We want to remove from the stream if we are siphoning the value off
  29. // (return false).
  30. if (!predicate.test(t)) {
  31. return true;
  32. }
  33. consumer.accept(t);
  34. return false;
  35. }
  36.  
  37. public static void main(String[] args) {
  38.  
  39. Predicate<Integer> p1 = (Integer i) -> {
  40. System.out.println("call p1");
  41. return i < 5;
  42. };
  43. Predicate<Integer> p2 = (Integer i) -> {
  44. System.out.println("call p2");
  45. return i > 5;
  46. };
  47. Consumer<Integer> c1 = i -> System.out.println("less");
  48. Consumer<Integer> c2 = i -> System.out.println("more");
  49.  
  50. IntStream.range(0, 10).boxed()
  51. .peek(new ConditionalTee<>(p1, c1))
  52. .forEach(new ConditionalTee<>(p2, c2));
  53. System.out.println(">>>>>>>>>>>>>>>>>>>>>>");
  54. IntStream.range(0, 10).boxed()
  55. .filter(new ConditionalTee<>(p1, c1))
  56. .forEach(new ConditionalTee<>(p2, c2));
  57. }
  58. }
  59.  
Success #stdin #stdout 0.21s 320640KB
stdin
Standard input is empty
stdout
call p1
less
call p2
call p1
less
call p2
call p1
less
call p2
call p1
less
call p2
call p1
less
call p2
call p1
call p2
call p1
call p2
more
call p1
call p2
more
call p1
call p2
more
call p1
call p2
more
>>>>>>>>>>>>>>>>>>>>>>
call p1
less
call p1
less
call p1
less
call p1
less
call p1
less
call p1
call p2
call p1
call p2
more
call p1
call p2
more
call p1
call p2
more
call p1
call p2
more