java8 stream获取List内元素的index
在Java 8中,可以通过使用IntStream.range()方法来获取List内元素的index。
下面是一个示例代码:
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("apple", "banana", "orange");
IntStream.range(0, list.size())
.forEach(i -> System.out.println("Index: " + i + ", Element: " + list.get(i)));
}
}
输出结果为:
Index: 0, Element: apple
Index: 1, Element: banana
Index: 2, Element: orange
在上面的代码中,我们使用IntStream.range()方法创建了一个从0到List的大小的整数流。然后,我们使用forEach()方法遍历整数流,并打印出每个元素的index和对应的List元素
原文地址: http://www.cveoy.top/t/topic/ib14 著作权归作者所有。请勿转载和采集!