Question

im new in Scala and im Looking for a way to do something like

val list = List(1, 0, 1, 2, 3, 1, 2, 0, 1, 2, 0, 3, 2, 0, 1)

mylist.sortWith(_ > _).partition(_ == 1).flatten

Problem is that partition() yields a tuple of lists but i need a list of lists.

The goal is to have this job done in one line without using other variable, optimisation in not a requirement.

A dirty/stupid way to achieve what im trying to do would be:

List(mylist.sortWith(_ > _).partition(_ == 1)._1, mylist.sortWith(_ > _).partition(_ == 1)._2).flatten

I am also wondering if i can cast the output of partition() to flatten it

Was it helpful?

Solution 2

It seems like a missing feature of Scala, "a method to convert a tuple to a list", but you can use productIterator to get there...sort of. ProductIterator returns a List[Any] so it's rather ugly but you could do something like:

  val list = List(1, 0, 1, 2, 3, 1, 2, 0, 1, 2, 0, 3, 2, 0, 1)

  list
    .sortBy(-_)
    .partition( _ == 1 )
    .productIterator.map( _.asInstanceOf[List[Int]] )
    .toList.flatten

 // Results in: List(1, 1, 1, 1, 1, 3, 3, 2, 2, 2, 2, 0, 0, 0, 0)

Just for a display of virtuosity you could also arrive at the same answer with

list.sortBy(-_).foldLeft(List[Int]()){case (a,1) => 1 +: a case (a,v) => a :+ v}

or:

list.sortBy(-_).sortWith((a,b) => a == 1)    

OTHER TIPS

Here's one way to do it:

list.sorted.groupBy(_ == 1).values.toList
  • sorted() simply sorts the list in ascending order (doable since it just contains Ints)
  • groupBy() converts this to a map of true -> 1's, false -> all else
  • values() returns the map's values
  • toList() converts this collection of the map's values into your desired list.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top