Java Stream Operation zip(List> streams)

Here you can find the source of zip(List> streams)

Description

Convert a List of Stream into a Stream of List by associating each element of one list with the element at the same position in the latters.

License

Open Source License

Parameter

Parameter Description
streams List of all streams we want to zip
T Type of items contained in the List

Return

Stream of list

Declaration

public static <T> Stream<List<T>> zip(List<Stream<T>> streams) 

Method Source Code

    //package com.java2s;
    //License from project: Open Source License 

    import java.util.ArrayList;

    import java.util.Iterator;
    import java.util.List;

    import java.util.Spliterator;
    import java.util.Spliterators;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    import java.util.stream.StreamSupport;

    public class Main {
        /**/*  w  w  w  .  ja  va2s  .  c o m*/
         * Convert a List of Stream into a Stream of List by associating each
         * element of one list with the element at the same position in the latters.
         * All streams in the lists should have the same length.
         *
         * @param streams
         *            List of all streams we want to zip
         * @param <T>
         *            Type of items contained in the List
         * @return Stream of list
         */
        public static <T> Stream<List<T>> zip(List<Stream<T>> streams) {
   final List<Iterator<T>> iteratorsList = streams.stream()
         .map(Stream::iterator).collect(Collectors.toList());
   final Iterator<List<T>> zippedIterator = new Iterator<List<T>>() {
      @Override
      public boolean hasNext() {
         for (Iterator<T> it : iteratorsList)
            if (it.hasNext())
               return true;
         return false;
      }

      @Override
      public List<T> next() {
         List<T> next = new ArrayList<>();
         for (Iterator<T> it : iteratorsList)
            next.add(it.next());
         return next;
      }
   };
   final boolean isParallel = true;
   return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
         zippedIterator, Spliterator.SORTED | Spliterator.DISTINCT),
         isParallel);
}
    }

Related

  1. toList(final Stream stream)
  2. toParameter(Stream input, Class exp)
  3. toString(IntStream s)
  4. toString(LongStream ls)
  5. upcastStream(Stream stream)
  6. zipWithIndex(Stream stream, int startIndex)