Print the String Array with index from java 8?

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

  • Take a String array input data.
  • Intstream.rangeClosed() method iterate the arrayString from 0 to Array Length.
  • Here mapToObj() convert each character into object.
  • Now String.format(“Index: %d, Value: %s”, i, arrayString[i]) created a format string,like Index: %d, Value: %s makes string format, i as an index value and arrayString[i] take char at give index i value.
  • Convert each String Array in the Stream to String.
  • Through forEach loop to print the output.
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

Print the String Array with index from java 8? Read More »