Kratos
Kratos

Reputation: 1114

Define a 2d list and append lists to it in a for loop, scala

I want to define a 2d list before a for loop and afterwards I want to append to it 1d lists in a for loop, like so:

var 2dEmptyList: listOf<List<String>> 
for (element<-elements){
    ///do some stuff
    2dEmptyList.plusAssign(1dlist) 
}

The code above does not work. But I can't seem to find a solution for this and it is so simple!

Upvotes: 2

Views: 2475

Answers (2)

Aliaksei Kuzmin
Aliaksei Kuzmin

Reputation: 609

If you want 2dEmptyList be mutable, please consider using scala.collection.mutable.ListBuffer:

scala> val ll = scala.collection.mutable.ListBuffer.empty[List[String]]
ll: scala.collection.mutable.ListBuffer[List[String]] = ListBuffer()

scala> ll += List("Hello")
res7: ll.type = ListBuffer(List(Hello))

scala> ll += List("How", "are", "you?")
res8: ll.type = ListBuffer(List(Hello), List(How, are, you?))

Upvotes: 1

airudah
airudah

Reputation: 1179

scala> val elements = List("a", "b", "c")
elements: List[String] = List(a, b, c)

scala> val twoDimenstionalList: List[List[String]] = List.empty[List[String]]
twoDimenstionalList: List[List[String]] = List()

scala> val res = for(element <- elements) yield twoDimenstionalList ::: List(element)
res: List[List[java.io.Serializable]] = List(List(a), List(b), List(c))

Better still:

scala> twoDimenstionalList ::: elements.map(List(_))
res8: List[List[String]] = List(List(a), List(b), List(c))

Upvotes: 1

Related Questions