简体   繁体   中英

Scala - How to group elements by occurrence?

Is there a function in scala that groups all elements of a list by the number of these occurrences?

For example, I have this list:

val x = List("c", "b", "b", "c", "a", "d", "c")

And I want to get a new list like that:

x = List((3, "c"), (2, "b"), (1, "a"), (1, "d"))

You can first count the occurrences of each element and then reverse the resulting tuples:

List("c", "b", "b", "c", "a", "d", "c")
  .groupBy(identity).mapValues(_.size) // Map(b -> 2, d -> 1, a -> 1, c -> 3)
  .toList                              // List((b,2), (d,1), (a,1), (c,3))
  .map{ case (k, v) => (v, k) }        // List((2,b), (1,d), (1,a), (3,c))

You don't specifically mention a notion of order for the output, but if this was a requirement, this solution would need to be adapted.

Try this to get exactly what you want in the order you mentioned. (ie., order preserved in the List while taking counts):

x.distinct.map(v=>(x.filter(_==v).size,v))

In SCALA REPL:

scala> val x = List("c", "b", "b", "c", "a", "d", "c")
x: List[String] = List(c, b, b, c, a, d, c)

scala> x.distinct.map(v=>(x.filter(_==v).size,v))
res225: List[(Int, String)] = List((3,c), (2,b), (1,a), (1,d))

scala>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM