Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a Scala Iterator to a Vector

Tags:

scala

vector

How do I convert a scala.collection.Iterator containing thousands of objects to a scala.collection.immutable.Vector?

I do not believe that I can use _* because of the number of items.

like image 340
Ralph Avatar asked Mar 12 '12 19:03

Ralph


2 Answers

You can

Vector() ++ myIterator

which gives the correct thing with the correct type. For very small vectors and iterators, in high-performance loops, you may instead wish to

val b = Vector.newBuilder[WhateverType]
while (myIterator.hasNext) { b += myIterator.next }
b.result

which does the minimum work necessary (as far as I know) to create a vector. toIndexedSeq does essentially this, but returns a more generic type (so you're not actually guaranteed a Vector, even if it does return a Vector now.)

like image 59
Rex Kerr Avatar answered Oct 29 '22 10:10

Rex Kerr


You can use toIndexedSeq. It doesn't statically return a Vector, but it actually is one.

like image 22
Jean-Philippe Pellet Avatar answered Oct 29 '22 11:10

Jean-Philippe Pellet