Java 8 forEach with index

Josh Stone picture Josh Stone · Apr 1, 2014 · Viewed 231.2k times · Source

Is there a way to build a forEach method in Java 8 that iterates with an index? Ideally I'd like something like this:

params.forEach((idx, e) -> query.bind(idx, e));

The best I could do right now is:

int idx = 0;
params.forEach(e -> {
  query.bind(idx, e);
  idx++;
});

Answer

srborlongan picture srborlongan · Apr 1, 2014

Since you are iterating over an indexable collection (lists, etc.), I presume that you can then just iterate with the indices of the elements:

IntStream.range(0, params.size())
  .forEach(idx ->
    query.bind(
      idx,
      params.get(idx)
    )
  )
;

The resulting code is similar to iterating a list with the classic i++-style for loop, except with easier parallelizability (assuming, of course, that concurrent read-only access to params is safe).