https://kotlinlang.org logo
#announcements
Title
# announcements
g

groostav

08/03/2019, 11:52 PM
if I have a
List<List<T>>
which can be conceptualized as a "list of columns", (where each inner
List<T>
is a column), whats the most elegant collection method to use to get a list of rows?
m

molikuner

08/04/2019, 12:49 AM
I would use sth. like
list.map { it[index] }
. EDIT: Sorry, understood that question wrong.
k

karelpeeters

08/04/2019, 6:33 AM
There are some edge cases that make this inconvenient, eg. lists with different sizes, an empty list and a list of empty lists. This works in the easy cases though:
Copy code
list.first().indiches.map { i -> list.map{ it[i] } }
m

molikuner

08/04/2019, 7:34 AM
list.flatMap { row -> row.mapIndexed { index, t -> index to t }}. groupBy({ it.first}) { it.second }.values
This sould return a list of rows, even when they aren't the same length or sth. is empty. But if you know, that the columns are all the same length, you should use Karels solution. It's way more efficient.
d

Dico

08/04/2019, 10:30 AM
I might consider a one dimensional array to store elements, then some iterators for both ways
2 Views