user6282166
user6282166

Reputation:

how to match of "n" list in SCALA every element with every element?

I am trying to combine "n" lists in Scala, but I'am beginner in this sintaxis. I have this:

For instance if I have "n" lists I want to combine all first elements, all seconds elements, etc.:

var a = List("book1","book2","book3","book4")
var b = List(103, 102, 101, 100)

I want to show for instance:

book1 103
book2 102
book3 101
book4 100

I did this method to read "n" lists but I just can show every list but not combine.

   def listar(x: List[column]): List[Any] = {
     if (x.isEmpty) List()
     else print(x.head.values)
     if (x.isEmpty) {
     List()
    } else {
    listar(x.tail)
      }
   }
  // Here I'm sending one list with more list, It's means list(list(),list(),list()...)
  listar(book.columns)    

How can I do it? Thanks you so much for your help.

The idea like this:

 var a = List("book1", "book2", "book3", "book4")
 var b = List(103, 102, 101, 100)
 var c = List ("otro1","otro2","otro3","otro4") 
 var d = List (1,2,3,4)

 var e = List(a,b,c,d)

book1 103 otro1 1
book2 102 otro2 2
How can I combine all firstElments, SecondsElement, etc....

Upvotes: 0

Views: 205

Answers (2)

Jeffrey Chung
Jeffrey Chung

Reputation: 19527

Use transpose:

val a = List("book1", "book2", "book3", "book4")
val b = List(103, 102, 101, 100)
val c = List("otro1", "otro2", "otro3", "otro4") 
val d = List(1, 2, 3, 4)

val e = List(a, b, c, d)
val combined = e.transpose
// List(List(book1, 103, otro1, 1), List(book2, 102, otro2, 2), List(book3, 101, otro3, 3), List(book4, 100, otro4, 4))

combined.foreach(println)
/* prints:
List(book1, 103, otro1, 1)
List(book2, 102, otro2, 2)
List(book3, 101, otro3, 3)
List(book4, 100, otro4, 4) */

combined is a List[List[Any]].

Upvotes: 2

prayagupadhyay
prayagupadhyay

Reputation: 31252

  • you can iterate on first list with an index
  • and map to second list with the index.

You will get a List((ElementFromFirstList, ElementFromSecondList)) eg,

scala> a.zipWithIndex.map { case (key: String, index: Int) => (key -> b(index)) }
res1: List[(String, Int)] = List((book1,103), (book2,102), (book3,101), (book4,100))

If you simple want Map of firstelem, secondelem

scala> a.zipWithIndex.map { case (key, index) => (key -> b(index)) }.toMap
res10: scala.collection.immutable.Map[String,Int] = Map(book1 -> 103, book2 -> 102, book3 -> 101, book4 -> 100)

I am assuming list1.size == list2.size

Upvotes: 0

Related Questions