Java Stream Operation zipWithIndex(Stream stream, int startIndex)

Here you can find the source of zipWithIndex(Stream stream, int startIndex)

Description

Zips the specified stream with its indices.

License

Open Source License

Declaration

public static <T> Stream<Map.Entry<Integer, T>> zipWithIndex(Stream<? extends T> stream, int startIndex) 

Method Source Code


//package com.java2s;
/*//w w  w. ja v  a  2s. co m
 * Copyright 2015 Alfresco Software, Ltd.  All rights reserved.
 *
 * License rights for this program may be obtained from Alfresco Software, Ltd. 
 * pursuant to a written agreement and any use of this program without such an 
 * agreement is prohibited. 
 */

import java.util.AbstractMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Spliterator;
import java.util.Spliterators;

import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class Main {
    /**
     * Zips the specified stream with its indices.
     */
    public static <T> Stream<Map.Entry<Integer, T>> zipWithIndex(Stream<? extends T> stream, int startIndex) {
        return iterate(new Iterator<Map.Entry<Integer, T>>() {
            private final Iterator<? extends T> streamIterator = stream.iterator();
            private int index = startIndex;

            @Override
            public boolean hasNext() {
                return streamIterator.hasNext();
            }

            @Override
            public Map.Entry<Integer, T> next() {
                return new AbstractMap.SimpleImmutableEntry<>(index++, streamIterator.next());
            }
        });
    }

    /**
     * Converts an {@link java.util.Iterator} to {@link java.util.stream.Stream}.
     */
    public static <T> Stream<T> iterate(Iterator<? extends T> iterator) {
        int characteristics = Spliterator.ORDERED | Spliterator.IMMUTABLE;
        return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, characteristics), false);
    }
}

Related

  1. toParameter(Stream input, Class exp)
  2. toString(IntStream s)
  3. toString(LongStream ls)
  4. upcastStream(Stream stream)
  5. zip(List> streams)