Print Multi-dimenstional Array in Kotlin?
Print Multi-dimenstional Array in Kotlin?
Given the array below what is the simplest way to print it? Looping is one option but is there any other simpler option?
val array = arrayOf(arrayOf(1, 2),
arrayOf(3, 4),
arrayOf(5, 6, 7))
3 Answers
3
1. Using standard library
val array = arrayOf(arrayOf(1, 2),
arrayOf(3, 4),
arrayOf(5, 6, 7))
print(Arrays.deepToString(array))
2. Using for loop
fun <T> print2DArray(twoDArray: Array<Array<T>>) {
for (i in 0 until twoDArray.size) {
for (j in 0 until twoDArray[i].size) {
print(twoDArray[i][j])
if (j != twoDArray[i].size - 1) print(" ")
}
if (i != twoDArray.size - 1) println()
}
}
val array = arrayOf(arrayOf(1, 2),
arrayOf(3, 4),
arrayOf(5, 6, 7))
print2DArray(array)
There is built-in functionality for this:
val array = arrayOf(arrayOf(1, 2),
arrayOf(3, 4),
arrayOf(5, 6, 7))
println(array.joinToString(prefix = "[", postfix = "]") {
it.joinToString(prefix = "[", postfix = "]")
})
println(Arrays.deepToString(twoDArray)) is giving me the same output as your code.
– Akshaysingh Yaduvanshi
Jul 3 at 9:17
Yep but my code is idiomatic Kotlin.
– Adam Arold
Jul 4 at 8:03
That depends on the way you want to show it.
fun Array.contentDeepToString: String
Returns a string representation of the contents of this array as if it is a List. Nested arrays are treated as lists too.
If any of arrays contains itself on any nesting level that reference is rendered as "[...]" to prevent recursion.
Note this is an inlined function using Arrays.deepToString(array)
under the hood.
Arrays.deepToString(array)
Then using array.contentDeepToString()
you get in the output this string:
array.contentDeepToString()
[[1, 2], [3, 4], [5, 6, 7]]
I mostly use Array.joinToString
, its allow to join the array using a given separator and applying a transformation to each element. From the doc:
Array.joinToString
Creates a string from all the elements separated using [separator] and using the given [prefix] and [postfix] if supplied. If the collection could be huge, you can specify a non-negative value of [limit], in which case only the first [limit]
elements will be appended, followed by the [truncated] string (which defaults to "...")
In your case as each item of your array is a subarray, you have to apply a transformation for them also using
array.joinToString("n") { subarray ->
subarray.joinToString()
}
This give you an output as:
1, 2
3, 4
5, 6, 7
You can play with separator, prefix, postfix, and transformation parameters to get your wanted format.
contentDeepToString
joinToString
joinToString
Iterable
Sequence
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Whoever down-voted can you please comment whats the reason for downvote ?
– JTeam
Jul 3 at 9:14