【问题标题】:Return position of an element in Arraylist using Lambda in Java在 Java 中使用 Lambda 返回 Arraylist 中元素的位置
【发布时间】:2018-01-27 23:32:17
【问题描述】:

我正在使用迭代器遍历我的 abc 类型的 allRecords 列表。跟踪元素 迭代,我保留一个位置变量。

我使用这个位置变量在我的程序中进一步应用一些逻辑。

代码sn-p如下:

Abc abc;
Iterator<Abc> iterator = allRecords.iterator();
while (iterator.hasNext()) {
  abc = iterator.next();
  position++;
  //validate the abc object with some conditions and break the loop if matches
  //I will have that position where the condition matched
}

我的问题是我可以使用一些 Java 最新的流 API 或 lambda 表达式来完成这项任务吗?

任何帮助将不胜感激。

【问题讨论】:

  • 流的重点是避免索引之类的东西,你想在这里实现什么?

标签: java lambda collections


【解决方案1】:

你可以通过这样的方式实现这一点

IntStream.range(0, allRecords.length)
     .filter(i -> allRecords[i].length() <= i)
     .mapToObj(i -> allRecords[i])

但是 Stream API 的设计使内部迭代成为可能,当你使用这个 api 时你不应该关心索引。

有关External and internal 迭代的更多信息,请参阅此帖子。

【讨论】:

    猜你喜欢
    • 2016-01-30
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 2016-02-05
    • 2011-09-25
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    相关资源
    最近更新 更多