Reputation: 135
I have 3 String arrays. I want to print the all the 3 single arrays one after another in java. So like my 2 arrays look like-
o
ooo
ooooo
ooo
o
o o
ooooo
ooo
ooooo
o oo
I want to print each element of the array one after another (right next to eachother)
Current code result-
o
ooo
ooooo
ooo
o
o o
ooooo
ooo
ooooo
o oo
o o
ooo
ooooo
ooo
o
So expected output
o o o o o
ooo ooooo oooo
ooooo ooo oooo
ooo ooooo oooo
The output above may differ from inputs, but its just the sample I am showing . This is how I am expecting to print.
current code-
String[] tp1 = { " o ", " ooo ", "ooooo", " ooo ", " o " };
String[] tp2 = { " o o", "ooooo", " ooo ", "ooooo", " o oo" };
String[] tp3 = { " o o ", " ooo ", "ooooo", " ooo ", " o " };
List<String[]> values = new ArrayList<>();
values.add(tp1);
values.add(tp2);
values.add(tp3);
for (String[] strings : values) {
String output = "";
for (String string : strings) {
output += string;
output += "\n";
}
System.out.print(output);
}
Upvotes: 0
Views: 5512
Reputation: 6121
Using Java 8 you can use the new forEach and a Lambda like this:
values.forEach(value -> {
Arrays.asList(value).forEach(array -> System.out.print(array));
System.out.println();
});
which results in
o ooo ooooo ooo o
o oooooo ooo ooooo o oo
o o ooo ooooo ooo o
If you realy want this:
o o o o o
ooo ooooo ooo
ooooo ooo ooooo
ooo ooooo ooo
o o oo o
You can do this like so:
for (int i=0; i<tp1.length; i++) {
final int j = i;
values.forEach(value -> System.out.print(value[j]));
System.out.println();
};
But then I would recommend you to flip the list and or the arrays. Since it is not clear if all arrays tp1..3 will have the same length. For example this way:
String[] tp1 = { " o ", " o o", " o o "};
String[] tp2 = { " ooo ", "ooooo", " ooo "};
String[] tp3 = { "ooooo", " ooo ", "ooooo" };
String[] tp4 = { " o ", " o oo" , " o " };
ArrayList<String[]> values = new ArrayList<>();
values.add(tp1);
values.add(tp2);
values.add(tp3);
values.add(tp4);
values.forEach(value -> {
Arrays.asList(value).forEach(array -> System.out.print(array));
System.out.println();
});
Upvotes: 1
Reputation: 3171
To get that output you don't require the values
variable. You have to output the 1st string of all the arrays in a single line so change your for
loop to
for (int i = 0; i < 5; i++) {
System.out.println(tp1[i]+tp2[i]+tp3[i]);
}
I feel this should solve your problem.
Upvotes: 0
Reputation: 14461
You need to invert your for loops. And hence you cannot you the for each
syntax.
Use,
for (int i = 0; i < tp1.length; i++) {
for (int j = 0; j < values.size(); j++) {
System.out.print(values.get(j)[i]);
}
System.out.println(" ");
}
Upvotes: 1