Merge pull request #15281 from Neetika23/print2DArray

Print2 d array
This commit is contained in:
Liam Williams 2024-01-12 15:53:38 +00:00 committed by GitHub
commit aad40a8de2
2 changed files with 71 additions and 1 deletions

View File

@ -7,6 +7,10 @@
<name>core-java-arrays-guides</name>
<packaging>jar</packaging>
<properties>
<system-stubs.jupiter.version>2.1.5</system-stubs.jupiter.version>
</properties>
<parent>
<artifactId>core-java-modules</artifactId>
<groupId>com.baeldung.core-java-modules</groupId>
@ -24,6 +28,13 @@
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator.version}</version>
</dependency>
<dependency>
<groupId>uk.org.webcompere</groupId>
<artifactId>system-stubs-jupiter</artifactId>
<version>${system-stubs.jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,59 @@
package com.baeldung.print2darrays;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import uk.org.webcompere.systemstubs.jupiter.SystemStub;
import uk.org.webcompere.systemstubs.jupiter.SystemStubsExtension;
import uk.org.webcompere.systemstubs.stream.SystemOut;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(SystemStubsExtension.class)
public class Print2DArraysUnitTest {
@SystemStub
private SystemOut systemOut;
@Test
void whenPrint2dArrayUsingNestedLoop_thenLinesAreWrittenToSystemOut() {
int[][] myArray = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
for (int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray[i].length; j++) {
System.out.print(myArray[i][j] + " ");
}
}
String expectedOutput = "1 2 3 4 5 6 7 8 9 ";
assertThat(systemOut.getLines()).containsExactly(expectedOutput);
}
@Test
public void whenPrint2dArrayUsingStreams_thenLinesAreWrittenToSystemOut() {
int[][] myArray = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
Arrays.stream(myArray)
.flatMapToInt(Arrays::stream)
.forEach(num -> System.out.print(num + " "));
String expectedOutput = "1 2 3 4 5 6 7 8 9 ";
assertThat(systemOut.getLines()).containsExactly(expectedOutput);
}
@Test
public void whenPrint2dArrayUsingDeepToString_thenLinesAreWrittenToSystemOut() {
int[][] myArray = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
System.out.println(Arrays.deepToString(myArray));
String expectedOutput = "[[1, 2, 3], [4, 5, 6], [7, 8, 9]]";
assertThat(systemOut.getLines()).containsExactly(expectedOutput);
}
@Test
public void whenPrint2dArrayUsingArrayToString_thenLinesAreWrittenToSystemOut() {
int[][] myArray = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
for (int[] row : myArray) {
System.out.print(Arrays.toString(row));
}
String expectedOutput = "[1, 2, 3][4, 5, 6][7, 8, 9]";
assertThat(systemOut.getLines()).containsExactly(expectedOutput);
}
}