Is there a concise way to iterate over a stream with indices in Java 8?

后端 未结 22 2608
天命终不由人
天命终不由人 2020-11-22 01:42

Is there a concise way to iterate over a stream whilst having access to the index in the stream?

String[] names = {\"Sam\",\"Pamela\", \"Dave\", \"Pascal\",          


        
22条回答
  •  耶瑟儿~
    2020-11-22 02:01

    I found the solutions here when the Stream is created of list or array (and you know the size). But what if Stream is with unknown size? In this case try this variant:

    public class WithIndex {
        private int index;
        private T value;
    
        WithIndex(int index, T value) {
            this.index = index;
            this.value = value;
        }
    
        public int index() {
            return index;
        }
    
        public T value() {
            return value;
        }
    
        @Override
        public String toString() {
            return value + "(" + index + ")";
        }
    
        public static  Function> indexed() {
            return new Function>() {
                int index = 0;
                @Override
                public WithIndex apply(T t) {
                    return new WithIndex<>(index++, t);
                }
            };
        }
    }
    

    Usage:

    public static void main(String[] args) {
        Stream stream = Stream.of("a", "b", "c", "d", "e");
        stream.map(WithIndex.indexed()).forEachOrdered(e -> {
            System.out.println(e.index() + " -> " + e.value());
        });
    }
    

提交回复
热议问题