// 示例代码:使用 Java 的 foreach 循环并获取索引
public class ForeachWithIndexExample {
public static void main(String[] args) {
String[] items = {"apple", "banana", "cherry"};
// 使用传统的 for 循环来获取索引
for (int i = 0; i < items.length; i++) {
System.out.println("Index " + i + ": " + items[i]);
}
// 使用增强型 for 循环(foreach),但不直接提供索引
// 如果需要索引,可以引入一个计数器变量
int index = 0;
for (String item : items) {
System.out.println("Index " + index + ": " + item);
index++;
}
// 或者使用 Java 8 的 Stream API 结合 IntStream 来获取索引
java.util.List<String> itemList = java.util.Arrays.asList(items);
java.util.stream.IntStream.range(0, itemList.size())
.forEach(i -> System.out.println("Index " + i + ": " + itemList.get(i)));
}
}
IntStream.range 和 forEach 方法,可以在遍历集合时同时获取索引。上一篇:java 静态内部类
下一篇:java 时间比较大小
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站