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

前端 未结 14 1371
旧巷少年郎
旧巷少年郎 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:57

    The methods of the class you mentioned have been moved to the Stream interface itself in favor to the default methods. But it seems that the zip method has been removed. Maybe because it is not clear what the default behavior for different sized streams should be. But implementing the desired behavior is straight-forward:

    static  boolean every(
      Collection c1, Collection c2, BiPredicate pred) {
        Iterator it=c2.iterator();
        return c1.stream().allMatch(x->!it.hasNext()||pred.test(x, it.next()));
    }
    static  T find(Collection c1, Collection c2, BiPredicate pred) {
        Iterator it=c2.iterator();
        return c1.stream().filter(x->it.hasNext()&&pred.test(x, it.next()))
          .findFirst().orElse(null);
    }
    

提交回复
热议问题