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

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

    The cleanest way is to start from a stream of indices:

    String[] names = {"Sam", "Pamela", "Dave", "Pascal", "Erik"};
    IntStream.range(0, names.length)
             .filter(i -> names[i].length() <= i)
             .mapToObj(i -> names[i])
             .collect(Collectors.toList());
    

    The resulting list contains "Erik" only.


    One alternative which looks more familiar when you are used to for loops would be to maintain an ad hoc counter using a mutable object, for example an AtomicInteger:

    String[] names = {"Sam", "Pamela", "Dave", "Pascal", "Erik"};
    AtomicInteger index = new AtomicInteger();
    List list = Arrays.stream(names)
                              .filter(n -> n.length() <= index.incrementAndGet())
                              .collect(Collectors.toList());
    

    Note that using the latter method on a parallel stream could break as the items would not necesarily be processed "in order".

提交回复
热议问题