Home > database >  Scala - how to copy from list_a to list_b in a loop using counter
Scala - how to copy from list_a to list_b in a loop using counter

Time:12-10

I am getting list of strings using that: val v = session(InfraExecConstants_v2.getSuAndSave).as[Vector[String]].toList

lets say that my list will look like that: list_a("1" , "2" , "3")

I would like to copy this list to a new list in a loop using a counter , like this:

  • list_a("1" , "2" , "3")
  • counter = 10
  • the code will use "list_a" and a "counter" to add the values in "list_b"

now list_b will look like that :

  • list_b("1" , "2" , "3", "1" , "2" , "3", "1" , "2" , "3", "1")

thanks

CodePudding user response:

In Scala when working with a List you probably do not want to use loops and counters. For one thing you want to avoid too low-level and imperative code in general, and List is just not well suited for it either.

For your specific use case I would create a lazy Iterator that infinitely repeats your list and then take the first 10 elements.

val listA = List(1, 2, 3)

val listB = Iterator.continually(listA).flatten.take(10).toList
// List(1, 2, 3, 1, 2, 3, 1, 2, 3, 1)

You still have to check that listA is not empty though, or you will loop forever or possibly run out of memory.

CodePudding user response:

Succinct but not terribly memory-efficient.

val list_b = List.fill(10)(list_a).flatten.take(10)

It works even if list_a is empty.

CodePudding user response:

I think the simplest solution based on Iterator is:

val listA: List[Int] = List(1, 2, 3)
val counter: Int = 10

val listB =
  Iterator
    .tabulate(counter)(n => listA(n % listA.size)) //access source list
    .toList

// List(1, 2, 3, 1, 2, 3, 1, 2, 3, 1)

Note: I noticed how popular the answers based on continually are but in my opinion given your question tabulate will better resemble a direct circular loop.

CodePudding user response:

There are quite a few answers, but I decided to share my solution anyway. Its advantage is that unnecessary elements are not created.

val list = List(1, 2, 3)
val counter = 10

val size = list.size
val howManyTimes = counter / size
val diff = counter % size

var listB = List[Int]()

if (diff > 0) {
  listB = List.fill(howManyTimes   1)(list).flatten.dropRight(size - diff)
} else {
  listB = List.fill(howManyTimes)(list).flatten
}

  • Related