Java 8 forEach 带索引 [英] Java 8 forEach with index

查看:36
本文介绍了Java 8 forEach 带索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Java 8 中构建一个使用索引进行迭代的 forEach 方法?理想情况下,我想要这样的东西:

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++;
});

推荐答案

由于您要迭代可索引的集合(列表等),因此我认为您可以只迭代元素的索引:

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)
    )
  )
;

生成的代码类似于使用经典的 i++ 样式的 for 循环迭代列表,除了更容易并行化(当然,假设对 params 的并发只读访问是安全的).

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).

这篇关于Java 8 forEach 带索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆