You can do an enhanced for loop (for java 5 and higher) for iteration on array's elements:

String[] elements = {"a", "a", "a", "a"};   
for (String s: elements) {           
    //Do your stuff here
    System.out.println(s); 
}
Answer from Michal on Stack Overflow
Top answer
1 of 2
11

A simple way would be to create a Pattern with the line separator and split the input String as a Stream. Then, each line is split with a space (keeping only 2 parts) and mapped to a MyObject. Finally, an array is constructed with the result.

public static void main(String[] args) {
    String str = "row1col1 row2col2\r\nrow2col1 row2col2\r\nrow3col1 row3col2";

    MyObject[] array =
        Pattern.compile(System.lineSeparator(), Pattern.LITERAL)
               .splitAsStream(str)
               .map(s -> s.split("\\s+", 2))
               .map(a -> new MyObject(a[0], a[1]))
               .toArray(MyObject[]::new);

    System.out.println(Arrays.toString(array));
}

Using splitAsStream can be advantageous over Stream.of(...) if the input String is long.

I assumed in the code that the line separator of the String was the default line separator (System.lineSeparator()) of the OS but you can change that if it is not.


Instead, if you are reading from a file, you could use Files.lines() to get a hold of a Stream of all the lines in the file:

MyObject[] array = Files.lines(path)
                        .map(s -> s.split("\\s+", 2))
                        .map(a -> new MyObject(a[0], a[1]))
                        .toArray(MyObject[]::new);

System.out.println(Arrays.toString(array));
2 of 2
7

You could generate a Stream of Strings that represent a single MyObject instance, and transform each of them to your MyObject instance (by first splitting them again and then constructing a MyObject instance) :

List<MyObject> list = 
   Stream.of(inputString.split("\n"))
      .map (s -> s.split(" "))
      .filter (arr -> arr.length == 2) // this validation may not be necessary
                                       // if you are sure each line contains 2 tokens
      .map (arr -> new MyObject(arr[0],arr[1]))
      .collect(Collectors.toList());
🌐
Benchresources
benchresources.net › home › java › java 8 – how to iterate over char[] arrays ?
Java 8 – How to Iterate over char[] Arrays ? - BenchResources.Net
September 26, 2022 - package in.bench.resources.string.to.character.array.conversion; public class IterateCharactersOfString1 { public static void main(String[] args) { // 1. test String String str = "BenchResources.Net"; System.out.println("Original String :- \n" + str); // 2. iterate using Java 8 Stream System.out.println("\nIterating over Characters of String :- "); str .chars() .forEach(ch -> System.out.print((char)ch + " ")); } }
People also ask

How do you iterate over a String array in Java?
There are several ways to iterate over a String array in Java. You can use a for-each loop, a simple for loop, or a while loop. A for-each loop simplifies iteration: for (String fruit : fruits) { System.out.println(fruit); }.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › string arrays in java
String Array in Java – How to Declare, Initialize, Iterate, and Use
Can you sort a String array in Java?
Yes, String arrays can be sorted in Java using Arrays.sort(). This method sorts the array in ascending alphabetical order. Example: Arrays.sort(fruits); sorts the array of fruits in alphabetical order. It works efficiently for any array of Strings.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › string arrays in java
String Array in Java – How to Declare, Initialize, Iterate, and Use
How can you initialize a String array in Java?
You can initialize a String array in two main ways: either by assigning values directly or through a loop. For example: String[] fruits = {"Apple", "Banana", "Cherry"}; or by creating an array with a predefined size and assigning values to each index.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › string arrays in java
String Array in Java – How to Declare, Initialize, Iterate, and Use
🌐
GeeksforGeeks
geeksforgeeks.org › java › iterate-over-the-characters-of-a-string-in-java
Iterate Over the Characters of a String in Java - GeeksforGeeks
July 23, 2025 - In this approach, we convert string to a character array using String.toCharArray() method. Then iterate the character array using for loop or for-each loop. ... // Java Program to Iterate Over the Characters of a String // Using String.toC...
🌐
Java67
java67.com › 2013 › 08 › how-to-iterate-over-array-in-java-15.html
How to iterate over an Array in Java using foreach loop Example Tutorial | Java67
Here is the complete code example of How to iterate over the String array in Java. Our array contains a list of programming languages, and we will loop over them and print their name. In the case of classical for loop, we will only go over until the middle of the array, just to show the power of counter in condition. By the way, this is not the only way to iterate or loop over an array in Java. There are many more ways like using for, while, do-while loop and newly added forEach() method of Java 8 Stream class.
🌐
Stack Overflow
stackoverflow.com › questions › 64388756 › string-array-iteration-in-java
String array iteration in Java - Stack Overflow
public static void main(String[] args) { Scanner sc=new Scanner(System.in); String[] arr=new String[60]; System.out.println("Enter no of elements"); int n=sc.nextInt(); sc.nextLine(); //<-- This line for(int i=0;i<n;i++) { arr[i]=sc.nextLine(); } for(int i=0;i<n;i++) System.out.println(arr[i]); } ... So I assume you enter your input in a new line each time (include the value of the number of elements). What you could do is just stick with .nextLine() and then convert that to an int for your n variable, like below. import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[] arr=new String[60]; System.out.println("Enter no of elements"); int n = Integer.parseInt(sc.nextLine()); for(int i = 0;i < n; i++) { arr[i] = sc.nextLine(); } for(int i = 0; i < n; i++) System.out.println(arr[i]); } }
🌐
Grails
grails.asia › iterate-through-string-array-in-java
Iterate Through String Array in Java - Grails Cookbook
July 28, 2017 - */ public class IterateStringArraySample { public static void main(String[] args) { String[] nameArray= {"John", "Paul", "Ringo", "George"}; int numberOfItems = nameArray.length; for (int i=0; i<numberOfItems; i++) { String name = nameArray[i]; System.out.println("Hello " + name); } } } Notice that we used the length attribute of the String array to get the number of items we have. Then we use a for loop to go through all the valid index from 0 upto length - 1. This is because Java is 0 based index language, which means index usually begins with 0 rather than 1.
🌐
TutorialKart
tutorialkart.com › java › how-to-iterate-over-string-array-in-java
How to Iterate over String Array in Java?
January 12, 2021 - To iterate over elements of String Array, use any of the Java Loops like while, for or advanced for loop.
Find elsewhere
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › string arrays in java
String Array in Java – How to Declare, Initialize, Iterate, and Use
May 14, 2025 - There are several ways to iterate over a String array in Java. You can use a for-each loop, a simple for loop, or a while loop.
🌐
GeeksforGeeks
geeksforgeeks.org › java › string-arrays-in-java
String Arrays in Java - GeeksforGeeks
October 2, 2025 - So generally we have three ways to iterate over a string array. The first method is to use a for-each loop. The second method is using a simple for loop. And the third method is to use a while loop.
🌐
Guru99
guru99.com › home › java tutorials › for-each loop in java
For-each loop in Java
November 8, 2024 - By : James Hartman UpdatedNovember 8, 2024 · Add Guru99 on Google · Add Guru99 on Google · For-Each Loop is another form of for loop used to traverse the array. for-each loop reduces the code significantly and there is no use of the index or rather the counter in the loop. For(<DataType of array/List><Temp variable name> : <Array/List to be iterated>){ System.out.println(); //Any other operation can be done with this temp variable. } Let us take the example using a String array that you want to iterate over without using any counters.
🌐
Vultr Docs
docs.vultr.com › java › examples › iterate-through-each-characters-of-the-string
Java Program to Iterate through each characters of the string | Vultr Docs
December 16, 2024 - Iterate over the array using an enhanced for loop. ... String str = "Hello, Java!"; char[] chars = str.toCharArray(); for (char c : chars) { System.out.println(c); } Explain Code
🌐
Java Handbook
javahandbook.com › java-strings › iteration-using-loops
Iteration (using loops)
August 24, 2025 - Learn Java string iteration using for loops and for-each loops. Master charAt() method, toCharArray() conversion, and character array manipulation.
🌐
W3Schools
w3schools.com › java › java_arrays_loop.asp
Java Loop Through an Array
However, it only gives you the values, not their positions (indexes) in the array. So, if you need both the position (index) of each element and its value, a regular for loop is the right choice. For example, when printing seat numbers in a theater row, you need to show both the seat number (the index) and who is sitting there (the value): String[] seats = {"Jenny", "Liam", "Angie", "Bo"}; for (int i = 0; i < seats.length; i++) { System.out.println("Seat number " + i + " is taken by " + seats[i]); }
🌐
Baeldung
baeldung.com › home › java › java string › how to iterate over the string characters in java
How to Iterate Over the String Characters in Java | Baeldung
May 11, 2024 - The toCharArray() method first converts the string into a character array, which we can use to perform the iteration. This method has a time complexity of O(n), where n is the length of the string str, and a space complexity of O(n) because ...
🌐
Delft Stack
delftstack.com › home › howto › java › for each char in string java
How to Iterate Over Characters of String in Java | Delft Stack
February 2, 2024 - import java.util.stream.IntStream; ... of the string. To iterate over every character in a string, we can use toCharArray() and display each character....
🌐
Edureka
edureka.co › blog › string-array-in-java
Java String Array | String Array in Java with Examples | Edureka
July 5, 2024 - Iteration over a string array is done by using java for loop, or java for each loop.
🌐
Javatechnote
javatechnote.com › home › print the string array with index from java 8?
Print String Array with index from java 8?
July 31, 2025 - 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 ...
🌐
TechBloat
techbloat.com › home › how to iterate string in java
How to Iterate String in Java - TechBloat
December 8, 2025 - If you’ve worked with Java strings in loops, you’ve probably noticed the traditional for loop or the iterator approach. But when it comes to iterating over a string’s characters, the enhanced for loop (or for-each) can be a game-changer — if used correctly. When to use it: The enhanced for loop is perfect for simple, read-only iterations over collections or arrays.