Zipping streams using JDK8 with lambda (java.util.stream.Streams.zip)

前端 未结 14 1566
旧巷少年郎
旧巷少年郎 2020-11-21 23:24

In JDK 8 with lambda b93 there was a class java.util.stream.Streams.zip in b93 which could be used to zip streams (this is illustrated in the tutorial Exploring Java8 Lambda

14条回答
  •  余生分开走
    2020-11-21 23:53

    AOL's cyclops-react, to which I contribute, also provides zipping functionality, both via an extended Stream implementation, that also implements the reactive-streams interface ReactiveSeq, and via StreamUtils that offers much of the same functionality via static methods to standard Java Streams.

     List> list =  ReactiveSeq.of(1,2,3,4,5,6)
                                                      .zip(Stream.of(100,200,300,400));
    
    
      List> list = StreamUtils.zip(Stream.of(1,2,3,4,5,6),
                                                      Stream.of(100,200,300,400));
    

    It also offers more generalized Applicative based zipping. E.g.

       ReactiveSeq.of("a","b","c")
                  .ap3(this::concat)
                  .ap(of("1","2","3"))
                  .ap(of(".","?","!"))
                  .toList();
    
       //List("a1.","b2?","c3!");
    
       private String concat(String a, String b, String c){
        return a+b+c;
       }
    

    And even the ability to pair every item in one stream with every item in another

       ReactiveSeq.of("a","b","c")
                  .forEach2(str->Stream.of(str+"!","2"), a->b->a+"_"+b);
    
       //ReactiveSeq("a_a!","a_2","b_b!","b_2","c_c!","c2")
    

提交回复
热议问题