gdlamp
gdlamp

Reputation: 617

Looking for a way to build a scala immutable.TreeMap from a list

So far the only way I can figure is using:

var ans: TreeMap[Int, Int] = immutable.TreeMap(List(1,2,3).map(e => (e, e*2)): _*)

1) Is there a way to do it without using the vararg _* syntax?

2) Is this pattern a good practice in scala?

Upvotes: 2

Views: 453

Answers (3)

Oleg Pyzhcov
Oleg Pyzhcov

Reputation: 7353

1) Is there a way to do it without using the vararg _* syntax?

Yes, you can use breakOut parameter to map. Note that this requires explicit type annotation on variable

import scala.collection.breakOut
import scala.collection.immutable.TreeMap

val ans: TreeMap[Int, Int] = List(1,2,3).map(e => (e, e*2))(breakOut)

2) Is this pattern a good practice in scala?

Until collections in Scala 2.13 allow you to write list.to(TreeMap), it's fine. I mean, it's not like there are better options, so use whatever solves your problem.

Upvotes: 3

Joe K
Joe K

Reputation: 18434

1) The other way would be creating an empty TreeMap and then adding all elements:

immutable.TreeMap.empty[Int, Int] ++ (List(1,2,3).map(e => (e, e*2)))

I don't have strong feelings about which way is better.

2) Yes, this is fairly common.

Upvotes: 1

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149628

Is there a way to do it without using the vararg _* syntax?

Since the apply method on TreeMap takes vararg of type (A, B)*, I don't see any other built in way

Is this pattern a good practice in scala?

I don't see why it wouldn't be.

An alternative would be to provide an extension method in the form of toTreeMap map which could work.

Upvotes: 1

Related Questions