I want process to two dimension list in scala: eg:
Input:
List(
List(‘John’, ‘Will’, ’Steven’),
List(25,28,34),
List(‘M’,’M’,’M’)
)
O/P:
John|25|M
Will|28|M
Steven|34|M
You need to work with indexes, and while working with indexes List is not probably the wisest choice, and also your input is not a well-structured two dimensional list, I would suggest you to have a dedicated data structure for this:
// you can name this better
case class Input(names: Array[String], ages: Array[Int], genders: Array[Char])
val input = Input(Array("John", "Will", "Steven"), Array(25, 28, 34), Array('M', 'M', 'M'))
By essence, this question is meant to use indexes with, so this would be a solution using indexes:
input.names.zipWithIndex.map {
case (name, index) =>
(name, inp.ages(index), inp.genders(index))
}
// or use a for instead
But always try to keep an eye on IndexOutOfBoundsException while working with array indexes. A safer and more "Scala-ish" approach would be zipping, which also take care of arrays with non-equal sizes:
input.names zip inp.ages zip inp.genders map { // flattening tuples
case ((name, age), gender) => (name, age, gender)
}
But this is a little bit slower (one iteration per zipping, and an iteration in mapping stage, I don't know if there's an optimization for this).
And in case you didn't want to go on with this kind of modeling, the algorithm would stay just the same, except for explicit unsafe conversions you will need to do from Any to String and Int and Char.
transpose?