Java8 forEach with index



我找不到一个forEach方法,该方法使用当前对象和当前索引调用lamda。

不幸的是,这在java8中没有实现,因此无法实现以下方法:

List<String> list = Arrays.asList("one", "two");
list.forEach((element, index) -> System.out.println(String.format("[%d] : %s", index, element)));

我知道一种简单的方法是将 for each 循环与索引整数一起使用:

List<String> list = Arrays.asList("one", "two");
int index = 0;
for (String element : list) {
System.out.println(String.format("[%d] : %s", index++, element));
}

我认为初始化索引 intetger 并为每次迭代递增它的通用代码应该移动到方法中。所以我定义了自己的forEach方法:

public static <T> void forEach(@NonNull Iterable<T> iterable, @NonNull ObjIntConsumer<T> consumer) {
int i = 0;
for (T t : iterable) {
consumer.accept(t, i++);
}
}

我可以像这样使用它:

List<String> list = Arrays.asList("one", "two");
forEach(list, (element, index) -> System.out.println(String.format("[%d] : %s", index, element)));

我无法在任何实用程序库(例如番石榴(中找到类似的实现。 所以我有以下问题:

  • 没有为我提供此功能的实用程序有什么原因吗?
  • 有没有理由在javaIterable.forEachmethdod中没有实现这一点?
  • 有没有我没有找到的提供此功能的好实用程序?

如果你想使用forEach你可以像这样使用IntStream

IntStream.range(0, list.size())
.forEach(index -> System.out.println(String.format("[%d] : %s", index, list.get(index))));

我在这篇文章中找到了一个 eclipse 集合中的 util 方法 有没有一种简洁的方法可以在 Java 8 中使用索引迭代流?

https://www.eclipse.org/collections/javadoc/7.0.0/org/eclipse/collections/impl/utility/Iterate.html#forEachWithIndex-java.lang.Iterable-org.eclipse.collections.api.block.procedure.primitive.ObjectIntProcedure-

Iterate.forEachWithIndex(people, (Person person, int index) -> LOGGER.info("Index: " + index + " person: " + person.getName()));

实现 https://github.com/eclipse/eclipse-collections/blob/master/eclipse-collections/src/main/java/org/eclipse/collections/impl/utility/internal/IteratorIterate.java 与我的util方法非常相似:

public static <T> void forEach(@NonNull Iterable<T> iterable, @NonNull ObjIntConsumer<T> consumer) {
int i = 0;
for (T t : iterable) {
consumer.accept(t, i++);
}
}

最新更新