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

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

问题描述

有没有办法在Java 8中建立一个 forEach 方法来迭代索引?理想情况下,我想这样的事情:

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

现在我可以做的最好的是:

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


解决方案

等等),我假设你可以只是迭代元素的指数:

pre $ Int $ c $ IntStream.range(0,params .size())
.forEach(idx - >
query.bind(
idx,
params.get(idx)


;

结果代码类似于使用经典的i ++ - for循环迭代列表,可并行性(当然,假设对params的并发只读访问是安全的)。

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

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天全站免登陆