how to print a String array with index in Java 8

Learn how to print a String array with index in Java 8 using IntStream.range(), mapToObj(), String.format() , and forEach() with example output.

Code Explanation (Step-by-Step)

  • A String array named arrayString is created with values like Java, String, Jsp, and Servlet.
  • IntStream.range (0, arrayString.length) generates index values from 0 to arrayString.length – 1.
  • mapToObj() converts each index into a formatted String.
  • format() is used to combine the index and array value in a readable format.
  • arrayString[i] gets the value present at the current index.
  • Use forEach(System.out::println) prints each formatted String one by one.
				
					import java.util.stream.IntStream;

public class Test {
	public static void main(String[] args) {
		String[] arrayString = { "Java", "String", "Jsp", "Servlet" };
		
		Stream<String> stringStream = IntStream.range(0, arrayString.length)
		        .mapToObj(i -> String.format("Index: %d, Value: %s", i, arrayString[i]));
		        
		stringStream.forEach(System.out::println);
	}
}
				
			

Output :-
Index: 0, Value: Java
Index: 1, Value: String
Index: 2, Value: Jsp
Index: 3, Value: Servlet

Java 8 Program to Print String Array with Index

				
					import java.util.Arrays;
import java.util.List;

public class Test {
    public static void main(String[] args) {

        String[] arrayString = { "Java", "String", "Jsp", "Servlet" };

        List<String> list = Arrays.asList(arrayString);

        list.forEach(value ->
                System.out.println("Index: " + list.indexOf(value) + ", Value: " + value)
        );
    }
}
				
			

Output :-
Index: 0, Value: Java
Index: 1, Value: String
Index: 2, Value: Jsp
Index: 3, Value: Servlet

FAQ :
How do you print a String array with index in Java 8?
You can print a String array with index in Java 8 by using IntStream.range() to generate indexes and then access each array value using arrayString[i].
Why do we use IntStream.range() in this program?
IntStream.range() is used to generate index values from 0 to arrayString.length – 1, which helps access both the index and value of the array.
What is the use of mapToObj() in this program?
mapToObj() converts each integer index into a formatted String containing the index and corresponding array value.