Is there a native grouping function that works like the sortWith function?

后端 未结 2 900
独厮守ぢ
独厮守ぢ 2020-12-21 20:45

There are a few libraries such as Spark and other Scala extensions that have the \"groupWith\" function available. This function allows you to compare an element to the rest

2条回答
  •  [愿得一人]
    2020-12-21 21:25

    Not sure if this what you want (check my comments to your question), but there is method groupBy defined in GenTraversableLike which List inherits (not only List). You will get:

    scala> val list = List(1,2,3,4,5,5)
    list: List[Int] = List(1, 2, 3, 4, 5, 5)
    
    scala> list.groupBy( el => el )
    res0: scala.collection.immutable.Map[Int,List[Int]] = Map(5 -> List(5, 5), 1 -> List(1), 2 -> List(2), 3 -> List(3), 4 -> List(4))
    
    scala> list.groupBy( el => el + 1 )
    res1: scala.collection.immutable.Map[Int,List[Int]] = Map(5 -> List(4), 6 -> List(5, 5), 2 -> List(1), 3 -> List(2), 4 -> List(3))
    

    Basically you need to provide discriminator function from value to key and you will get Map[Key, List[Value].

    Is this what you want?

提交回复
热议问题