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

后端 未结 22 2333
天命终不由人
天命终不由人 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 01:55

    If you need the index in the forEach then this provides a way.

      public class IndexedValue {
    
        private final int    index;
        private final Object value;
    
        public IndexedValue(final int index, final Object value) { 
            this.index = index;
            this.value = value;
        }
    
        public int getIndex() {
            return index;
        }
    
        public Object getValue() {
            return value;
        }
    }
    

    Then use it as follows.

    @Test
    public void withIndex() {
        final List list = Arrays.asList("a", "b");
        IntStream.range(0, list.size())
                 .mapToObj(index -> new IndexedValue(index, list.get(index)))
                 .forEach(indexValue -> {
                     System.out.println(String.format("%d, %s",
                                                      indexValue.getIndex(),
                                                      indexValue.getValue().toString()));
                 });
    }
    

提交回复
热议问题