Java8 forEach with index

问题描述 投票:0回答:2

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

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

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

我知道一个简单的方法是对每个循环使用一个索引整数:

List<String> list = Arrays.asList("one", "two");

int index = 0;
for (String element : list) {
   System.out.println(String.format("[%d] : %s", index++, element));
}

我认为用于初始化索引整数并为每次迭代递增索引的通用代码应移至方法中。因此,我定义了自己的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)));

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

  • 有没有理由没有提供我此功能的实用程序?
  • 有没有在JavaIterable.forEachmethdod中未实现此功能的原因?
  • 我没有找到一个好的工具可以提供此功能吗?
java foreach java-8
2个回答
3
投票

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

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

0
投票

[我在这篇文章Is there a concise way to iterate over a stream with indices in Java 8?中在Eclipse集合中找到了util方法

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++);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.