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 OverflowYou 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);
}
String[] elements = { "a", "a", "a", "a" };
for( int i = 0; i < elements.length - 1; i++)
{
String element = elements[i];
String nextElement = elements[i+1];
}
Note that in this case, elements.length is 4, so you want to iterate from [0,2] to get elements 0,1, 1,2 and 2,3.
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));
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());