Program to Print String Array with Index in Java 8

Program to Print String Array with index in java 8, we are using the following approach.

  • Take a String array as input.
  • Use Intstream.range() method iterate from 0 to arrayString.length-1.
  • Use mapToObj() to convert each index into a formatted String.
  • String.format(“Index: %d, Value: %s”, i, arrayString[i]) creates the output String, where i is the index and arrayString[i] is the value at that index.
  • Use forEach() to print each formatted string.
import java.util.stream.IntStream;
import java.util.stream.Stream;

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

Program to Print String Array with Index in Java 8 Read More »