scala-collections

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

心不动则不痛 提交于 2019-12-03 03:34:10
问题 I have a Seq containing objects of a class that looks like this: class A (val key: Int, ...) Now I want to convert this Seq to a Map , using the key value of each object as the key, and the object itself as the value. So: val seq: Seq[A] = ... val map: Map[Int, A] = ... // How to convert seq to map? How can I does this efficiently and in an elegant way in Scala 2.8? 回答1: Map over your Seq and produce a sequence of tuples. Then use those tuples to create a Map . Works in all versions of Scala.

Scala Nil equivalent for Set

五迷三道 提交于 2019-12-03 01:15:00
Is there an equivalent of Nil for Set in scala? I tried using Nil as a value for Set , but I got an error (expected since the type of Nil is List ) Thanks Set.empty is that set; although you can't get at it directly, it turns out that it is just a private object in the Set companion object (called, obviously enough, EmptySet ). All that Set.empty does is return that set with a cast to the correct type. It is done this way, instead of with Nil , because sets are invariant in their parameters. Nil is List[Nothing]() , but you couldn't add anything to a Set[Nothing]() . If you need to specify the

How to write a zipWith method that returns the same type of collection as those passed to it?

隐身守侯 提交于 2019-12-03 01:03:01
I have reached this far: implicit def collectionExtras[A](xs: Iterable[A]) = new { def zipWith[B, C, That](ys: Iterable[B])(f: (A, B) => C)(implicit cbf: CanBuildFrom[Iterable[A], C, That]) = { val builder = cbf(xs.repr) val (i, j) = (xs.iterator, ys.iterator) while(i.hasNext && j.hasNext) { builder += f(i.next, j.next) } builder.result } } // collectionExtras: [A](xs: Iterable[A])java.lang.Object{def zipWith[B,C,That](ys: Iterable[B])(f: (A, B) => C)(implicit cbf: scala.collection.generic.CanBuildFrom[Iterable[A],C,That]): That} Vector(2, 2, 2).zipWith(Vector(4, 4, 4))(_ * _) // res3:

How do I convert a java.util.Map to scala.collection.immutable.Map in Java?

旧街凉风 提交于 2019-12-03 00:30:38
I find lots of people trying to do this, and asking about this but the question is always answered in terms of scala code. I need to call an API that is expecting a scala.collection.immutable.Map but I have a java.util.Map, how can I cleanly convert from the latter to the former in my java code? The compiler disagrees with the sentiment that it is an implicit conversion as it barfs on that when I try it! Thank you! Getting an immutable Scala map is a little tricky because the conversions provided by the collections library return all return mutable ones, and you can't just use toMap because it

idiomatic “get or else update” for immutable.Map?

旧时模样 提交于 2019-12-02 22:41:10
What is the idiomatic way of a getOrElseUpdate for immutable.Map instances?. I use the snippet below, but it seems verbose and inefficient var map = Map[Key, Value]() def foo(key: Key) = { val value = map.getOrElse(key, new Value) map += key -> value value } Let me summarise your problem: You want to call a method on a immutable data structure You want it to return some value and reassign a var Because the data structure is immutable, you’ll need to return a new immutable data structure, or do the assignment inside the method, using a supplied closure So, either your signature has to look like

Scala performance question

强颜欢笑 提交于 2019-12-02 22:31:31
In the article written by Daniel Korzekwa , he said that the performance of following code: list.map(e => e*2).filter(e => e>10) is much worse than the iterative solution written using Java. Can anyone explain why? And what is the best solution for such code in Scala (I hope it's not a Java iterative version which is Scala-fied)? The reason that particular code is slow is because it's working on primitives but it's using generic operations, so the primitives have to be boxed. (This could be improved if List and its ancestors were specialized.) This will probably slow things down by a factor of

What is the fastest way to sum a collection in Scala

偶尔善良 提交于 2019-12-02 21:24:12
I've tried different collections in Scala to sum it's elements and they are much slower than Java sums it's arrays (with for cycle). Is there a way for Scala to be as fast as Java arrays? I've heard that in scala 2.8 arrays will be same as in java, but they are much slower in practice Indexing into arrays in a while loop is as fast in Scala as in Java. (Scala's "for" loop is not the low-level construct that Java's is, so that won't work the way you want.) Thus if in Java you see for (int i=0 ; i < array.length ; i++) sum += array(i) in Scala you should write var i=0 while (i < array.length) {

Extract numbers from String Array

左心房为你撑大大i 提交于 2019-12-02 20:37:05
问题 I have a Array of Strings scala> tokens res34: Array[String] = Array(The, value, of, your, profile, is, 234.2., You, have, potential, to, gain, 8.3, more.) Here each of comma separated value is a String. I want to extract numbers from this i.e. my output should be result = (234.2, 8.3) & it should be mutable so that I can read from another array and append values What data structure should I use to achieve this? 回答1: Consider import scala.util._ tokens.flatMap(s => Try( s.split("\\W+")

Cleaner tuple groupBy

大城市里の小女人 提交于 2019-12-02 18:52:56
I have a sequence of key-value pairs (String, Int), and I want to group them by key into a sequence of values (i.e. Seq[(String, Int)]) => Map[String, Iterable[Int]]) ). Obviously, toMap isn't useful here, and groupBy maintains the values as tuples. The best I managed to come up with is: val seq: Seq[( String, Int )] // ... seq.groupBy( _._1 ).mapValues( _.map( _._2 ) ) Is there a cleaner way of doing this? Here's a pimp that adds a toMultiMap method to traversables. Would it solve your problem? import collection._ import mutable.Builder import generic.CanBuildFrom class TraversableOnceExt[CC,

Behaviour of withDefaultValue in mutable.Map

纵然是瞬间 提交于 2019-12-02 18:27:59
问题 Can anyone explain how a default value in mutable map works? scala> val mmap = mutable.Map[String, mutable.Set[String]]().withDefaultValue{mutable.Set[String]()} mmap: scala.collection.mutable.Map[String,scala.collection.mutable.Set[String]] = Map() scala> mmap("a") += "b" res1: scala.collection.mutable.Set[String] = Set(b) Map is empty, no keys. scala> mmap res2: scala.collection.mutable.Map[String,scala.collection.mutable.Set[String]] = Map() But the key I just tried to edit is showing data