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

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

    public class Tuple {
        private final S object1;
        private final T object2;
    
        public Tuple(S object1, T object2) {
            this.object1 = object1;
            this.object2 = object2;
        }
    
        public S getObject1() {
            return object1;
        }
    
        public T getObject2() {
            return object2;
        }
    }
    
    
    public class StreamUtils {
    
        private StreamUtils() {
        }
    
        public static  Stream> zipWithIndex(Stream stream) {
            Stream integerStream = IntStream.range(0, Integer.MAX_VALUE).boxed();
            Iterator integerIterator = integerStream.iterator();
            return stream.map(x -> new Tuple<>(integerIterator.next(), x));
        }
    }
    

提交回复
热议问题