Java 8 extending stream

后端 未结 3 2000
慢半拍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:59

    Another possibility is, if you don't want to handle all the Stream delegates and new methods in the future, to use an Interface with a more wrapped lambda stream method:

    public interface MyStream {
    
        Stream stream();
    
        static  MyStream of(Stream stream) {
            return () -> stream;
        }
    
        default  MyStream stream(Function, Stream> stream) {
            return of(stream.apply(stream()));
        }
    
        //Watch out with Double cast. Check the type in method or restrict it via generic
        default MyStream biggerThanFour() {
            return of(stream().filter(i -> ((Double) i > 4)));
        }
    
        //Watch out with Double cast. Check the type in method or restrict it via generic
        //Another method
        default MyStream biggerThanFourteen() {
            return of(stream().filter(i -> ((Double) i > 14)));
        }
    }
    

    So you have your Interface with your delegate here stream() method which also handles the base stream terminal methods,
    the static creation method of(...),
    again a stream(...) method but with a Function as parameter for handling the base Stream intermediate methods
    and of course your custom methods like biggerThanFour(). So the drawback is here that you cant extend directly from Stream (unfortunately the Stream has not only default methods for one standard implementation) to bypass the delegates.
    Also the handling is a small drawback but I think in most cases it's fine e.g.:

    List doubles = MyStream.of(Stream.of(1.0, 3.0, 7.0, 2.0, 9.0)) // create instance
                    .biggerThanFour() //call MyStream methods
                    .stream(doubleStream -> doubleStream.map(aDouble -> aDouble * 2)) //Do youre base stream intermediate methods and return again MyStream so you can call more specific custom methods
                    .biggerThanFourteen()
                    .stream() // call the base stream more or less your delegate for last intermediate methods and terminal method
                    .mapToInt(Double::intValue)
                    .boxed() //Ah if you have IntStreams and similar you can call the boxed() method to get an equivalent stream method.
                    .collect(Collectors.toList()); // terminal method call
    

    So list content is [18] ;)

提交回复
热议问题