JohnDo
JohnDo

Reputation: 25

Sorting list by most frequent element first - Scala

I want to sort a list which takes an ordinary list for example:

List("5", "3", "3", "6", "3", "5")

And sorts it by the highest element first and turns it into something like this:

List("3", "5", "6")

I have tried doing something along the lines of

val key = list.groupBy(indentity).mapValues(_.size)
val newList = key.KeySet.toList

But this doesn't end up sorting the list in order (I think because KeySet sorts it randomly first, not entirely sure though). Thanks!

Upvotes: 0

Views: 105

Answers (2)

Guru Stron
Guru Stron

Reputation: 142213

You can sort map elements before producing the list:

val list  = List("5", "3", "3", "6", "3", "5")
val key = list.groupBy(identity)
  .view
  .mapValues(_.size)
  .toSeq
  .sortBy(_._2)(Ordering.Int.reverse)
  .map(_._1)
  .toList

Upvotes: 1

gatear
gatear

Reputation: 946

So sort based on the occurrences?

Compute the occurrences:

val occ = 
  List("5", "3", "3", "6", "3", "5")
    .groupBy(identity)
    .mapValues(_.size)
//Map(5 -> 2, 6 -> 1, 3 -> 3)    

and sort based on the occ:

occ
  .toList
  .sortBy { case (value, occ) => -occ }
  .map(_._1)
//List(3, 5, 6)

Upvotes: 2

Related Questions