Java 8 extending stream

后端 未结 3 2005
慢半拍i
慢半拍i 2021-02-15 17:24

I\'m attempting to extend Java 8\'s Stream implementation.

I have this interface:

public interface StreamStuff extends Stream {

    St         


        
3条回答
  •  我寻月下人不归
    2021-02-15 17:44

    As already mentioned, you can create your own wrapper implementation:

    public class MyStream implements Stream {
    
        private final Stream delegate;
    
        public MyStream(Stream delegate) {
            this.delegate = delegate;
        }
    
        @Override
        public Stream filter(Predicate predicate) {
            return delegate.filter(predicate);
        }
    
        @Override
        public void forEach(Consumer action) {
            delegate.forEach(action);
        }
    
        MyStream biggerThanFour() {
            return new MyStream<>(delegate.filter(i -> ((Double) i > 4)));
        }
    
        // all other methods from the interface
    }
    

    You will have to delegate all methods from the interface, so the class will be pretty big. You might consider adding a class StreamWrapper which will delegate all methods from the interface and then have your actual class StreamStuff extend StreamWrapper. This would allow you to have only your custom methods in StreamStuff and no other stream methods. You might also make all overridden methods in StreamWrapper final to avoid accidentally overriding them.

    Then you can use it like this:

    public static void main(String[] args) {
        Stream orgStream = Stream.of(1.0, 3.0, 7.0, 2.0, 9.0);
    
        MyStream myStream = new MyStream<>(orgStream);
    
        myStream.biggerThanFour().forEach(System.out::println);
    }
    

    The custom method returns a new wrapper so you can chain calls to your custom methods.

    Just note that your cast to Double might throw ClassCastException so you might consider replacing generic T with Double, hence limiting the delegate stream to be of that specific type.

提交回复
热议问题