How to convert a Seq[A] to a Map[Int, A] using a value of A as the key in the map?

Since 2.8 Scala has had .toMap, so: val map = seq.map(a => a.key -> a).toMap or if you’re gung ho about avoiding constructing an intermediate sequence of tuples, then in Scala 2.8 through 2.12: val map: Map[Int, A] = seq.map(a => a.key -> a)(collection.breakOut) or in Scala 2.13 and 3 (which don’t have breakOut, but … Read more

Convert Java Map to Scala Map

Edit: the recommended way is now to use JavaConverters and the .asScala method: import scala.collection.JavaConverters._ val myScalaMap = myJavaMap.asScala.mapValues(_.asScala.toSet) This has the advantage of not using magical implicit conversions but explicit calls to .asScala, while staying clean and consise. The original answer with JavaConversions: You can use scala.collection.JavaConversions to implicitly convert between Java and Scala: … Read more

Use-cases for Streams in Scala

The main difference between a Stream and an Iterator is that the latter is mutable and “one-shot”, so to speak, while the former is not. Iterator has a better memory footprint than Stream, but the fact that it is mutable can be inconvenient. Take this classic prime number generator, for instance: def primeStream(s: Stream[Int]): Stream[Int] … Read more

Scala Map foreach

I’m not sure about the error, but you can achieve what you want as follows: m.foreach(p => println(“>>> key=” + p._1 + “, value=” + p._2)) That is, foreach takes a function that takes a pair and returns Unit, not a function that takes two arguments: here, p has type (String, Int). Another way to … Read more

Scala Sets contain the same elements, but sameElements() returns false

The Scala collections library provides specialised implementations for Sets of fewer than 5 values (see the source). The iterators for these implementations return elements in the order in which they were added, rather than the consistent, hash-based ordering used for larger Sets. Furthermore, sameElements (scaladoc) is defined on Iterables (it is implemented in IterableLike – … Read more

tech