Reputation: 1224
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
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