|
| 1 | +import java.util.ArrayList; |
| 2 | +import java.util.List; |
| 3 | +import java.util.Objects; |
| 4 | +import java.util.function.Function; |
| 5 | +import java.util.function.Predicate; |
| 6 | + |
| 7 | +public class ReferencePipeline implements Stream { |
| 8 | + |
| 9 | + protected ReferencePipeline previousStage; |
| 10 | + |
| 11 | + private List<StreamObject> objects; |
| 12 | + |
| 13 | + private ReferencePipeline(List<StreamObject> objects) { |
| 14 | + this.objects = objects; |
| 15 | + } |
| 16 | + |
| 17 | + public ReferencePipeline() { |
| 18 | + } |
| 19 | + |
| 20 | + public Sink opWrapSink(Sink sink) { |
| 21 | + throw new UnsupportedOperationException(); |
| 22 | + } |
| 23 | + |
| 24 | + public static ReferencePipeline of(List<StreamObject> objects) { |
| 25 | + return new ReferencePipeline(objects); |
| 26 | + } |
| 27 | + |
| 28 | + public Stream filter(Predicate<StreamObject> predicate) { |
| 29 | + return new Operation(this) { |
| 30 | + @Override |
| 31 | + public Sink opWrapSink(Sink sink) { |
| 32 | + return new ChainedReference(sink) { |
| 33 | + |
| 34 | + @Override |
| 35 | + public void accept(Object o) { |
| 36 | + if (predicate.test((StreamObject) o)) |
| 37 | + downstream.accept(o); |
| 38 | + } |
| 39 | + }; |
| 40 | + } |
| 41 | + }; |
| 42 | + } |
| 43 | + |
| 44 | + public Stream map(Function function) { |
| 45 | + return new Operation(this) { |
| 46 | + @Override |
| 47 | + public Sink opWrapSink(Sink sink) { |
| 48 | + return new ChainedReference(sink) { |
| 49 | + |
| 50 | + @Override |
| 51 | + public void accept(Object o) { |
| 52 | + downstream.accept(function.apply(o)); |
| 53 | + } |
| 54 | + }; |
| 55 | + } |
| 56 | + }; |
| 57 | + } |
| 58 | + |
| 59 | + public List<Object> toList() { |
| 60 | + final List<Object> result = new ArrayList<>(); |
| 61 | + |
| 62 | + Sink finalSink = o -> result.add(o); |
| 63 | + |
| 64 | + ReferencePipeline previousStage = this; |
| 65 | + Sink sink = finalSink; |
| 66 | + |
| 67 | + while (previousStage.previousStage != null) { |
| 68 | + sink = previousStage.opWrapSink(sink); |
| 69 | + previousStage = previousStage.previousStage; |
| 70 | + } |
| 71 | + |
| 72 | + for (StreamObject object : previousStage.objects) { |
| 73 | + sink.accept(object); |
| 74 | + } |
| 75 | + |
| 76 | + return result; |
| 77 | + } |
| 78 | + |
| 79 | + abstract class Operation extends ReferencePipeline { |
| 80 | + |
| 81 | + public Operation(ReferencePipeline previousStage) { |
| 82 | + this.previousStage = previousStage; |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + abstract class ChainedReference implements Sink { |
| 87 | + protected final Sink downstream; |
| 88 | + |
| 89 | + public ChainedReference(Sink downstream) { |
| 90 | + this.downstream = Objects.requireNonNull(downstream); |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | +} |
0 commit comments