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

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

    I humbly suggest this implementation. The resulting stream is truncated to the shorter of the two input streams.

    public static <L, R, T> Stream<T> zip(Stream<L> leftStream, Stream<R> rightStream, BiFunction<L, R, T> combiner) {
        Spliterator<L> lefts = leftStream.spliterator();
        Spliterator<R> rights = rightStream.spliterator();
        return StreamSupport.stream(new AbstractSpliterator<T>(Long.min(lefts.estimateSize(), rights.estimateSize()), lefts.characteristics() & rights.characteristics()) {
            @Override
            public boolean tryAdvance(Consumer<? super T> action) {
                return lefts.tryAdvance(left->rights.tryAdvance(right->action.accept(combiner.apply(left, right))));
            }
        }, leftStream.isParallel() || rightStream.isParallel());
    }
    
    0 讨论(0)
  • 2020-11-21 23:59

    Using the latest Guava library (for the Streams class) you should be able to do

    final Map<String, String> result = 
        Streams.zip(
            collection1.stream(), 
            collection2.stream(), 
            AbstractMap.SimpleEntry::new)
        .collect(Collectors.toMap(e -> e.getKey(), e  -> e.getValue()));
    
    0 讨论(0)
提交回复
热议问题