BlueTriangles
BlueTriangles

Reputation: 1224

Scala - Create list from for loop

Is there an easy way to create a list from a for-loop that, in each iteration of the loop, iterates on an iterator?

For example, let's say I have an iterator that returns a random double each time it is called:

val randDoubleIterator = new Iterator[Double] {
    override def hasNext: Boolean = true
    override def next(): Double = {
        Random.nextDouble
    }
}

Let's say I want to create a list of 10 random doubles. I could loop through the iterator to get 10 random doubles, adding each to my list (myList) as I go:

// The following is pseudocode
val myList = new List

for (i <- 0 until 10) {
    myList.add(randDoubleIterator.next())
}

Is there an easier, more succinct way of doing this?

Upvotes: 1

Views: 1130

Answers (2)

jwvh
jwvh

Reputation: 51271

I believe this is both easier and more succinct.

val randDoubleIterator = Iterator.continually(util.Random.nextDouble)

val myList = randDoubleIterator.take(10).toList

This assumes that you want to keep randDoubleIterator around for other purposes later in the code.

Upvotes: 3

TheInnerLight
TheInnerLight

Reputation: 12184

How about this:

List.fill(10)(Random.nextDouble())

Upvotes: 5

Related Questions