ในการวนซ้ำ Stream with Indices ใน Java 8 โค้ดจะเป็นดังนี้ −
ตัวอย่าง
import java.util.stream.IntStream;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Demo{
public static void main(String[] args){
String[] my_array = { "T", "h", "i", "s", "s","a", "m", "p", "l", "e" };
AtomicInteger my_index = new AtomicInteger();
System.out.println("The elements in the string array are :");
Arrays.stream(my_array).map(str -> my_index.getAndIncrement() + " -> " + str).forEach(System.out::println);
}
} ผลลัพธ์
The elements in the string array are : 0 -> T 1 -> h 2 -> i 3 -> s 4 -> s 5 -> a 6 -> m 7 -> p 8 -> l 9 -> e
คลาสชื่อ Demo มีฟังก์ชันหลัก ในฟังก์ชันหลักนี้ อาร์เรย์ของประเภทสตริงจะถูกประกาศและอินสแตนซ์ AtomicInteger จะถูกสร้างขึ้นโดยใช้คลาส AtomicInteger ฟังก์ชัน 'getAndIncrement' ใช้เพื่อวนซ้ำองค์ประกอบของอาร์เรย์สตริงและทุกองค์ประกอบที่ทำซ้ำจะถูกพิมพ์ลงบนคอนโซล