11

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.

4 Answers 4

15

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.)

Sign up to request clarification or add additional context in comments.

Comments

6

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

2 Comments

Chances are OP does indeed just want some indexed sequence, and not necessarily a Vector specifically.
You are right. I need (near) constant-time random access and length calculations.
1

You can use _*, since all it does is pass a Seq with all the arguments. It will be inefficient, however, since it will first convert the iterator into a sequence, and then use that sequence to create another sequence.

Comments

0

Iterator supports .toVector now since at minimum Scala 11 (and maybe earlier).

class Thing val myIterator = Iterator(new Thing, new Thing, new Thing) myIterator.toVector 

produces:

res1: scala.collection.immutable.Vector[Thing] = Vector(Thing@22da2fe6, Thing@100ad67e, Thing@713a35c5) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.