Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List any type sort

Tags:

scala

I've got a list. but the type is any.

// list: List[List[Any]] = List(List(b, 50), List(a, 25), List(i, 60))
val list = List( List("b", 50), List("a", 25), List("i", 60))


// sort should be list(0)(0) "String" sort
("a", 25), ("b", 50), ("i", 60)

// or  list(0)(1) "Integer" sort
("a", 25), ("b", 50), ("i", 60)

I want to sort. How can I do? Thank you in advance.

like image 354
yasaricli Avatar asked Feb 13 '26 22:02

yasaricli


2 Answers

Trying to sort a list like this is inherently unsafe since the compiler cannot guarantee that the elements of the inner lists have the correct types. Perhaps the safest way to accomplish this would be do use a match to convert the particular element, and to raise an exception is the data is not what is should be.

list.sortBy(x =>
  x(0) match {
    case s: String => s
    case _ => sys.error("not a string")
  })                                            
//> res0: List[List[Any]] = List(List(a, 25), List(b, 50), List(i, 60))

list.sortBy(x =>
  x(1) match {
    case i: Int => i
    case _ => sys.error("not an integer")
  })                                            
//> res1: List[List[Any]] = List(List(a, 25), List(b, 50), List(i, 60))

That said, it sounds like what you really need is a list of (String, Int) tuples. That way the compiler can guarantee safety:

val list2 = List(("b", 50), ("a", 25), ("i", 60))                                                  
//> list2  : List[(java.lang.String, Int)] = List((b,50), (a,25), (i,60))

Notice that the compiler knows the types of the inner elements. So sorting is much easier, and safer:

list2.sortBy(_._1)                              
//> res2: List[(java.lang.String, Int)] = List((a,25), (b,50), (i,60))
list2.sortBy(_._2)                              
//> res3: List[(java.lang.String, Int)] = List((a,25), (b,50), (i,60))
like image 53
dhg Avatar answered Feb 16 '26 11:02

dhg


To sort by first and second elements use this:

scala> list.sortBy{
     |   case (s: String) :: (i: Int) :: Nil => s -> i
     |   case _ => sys.error("error")
     | }
res0: List[List[Any]] = List(List(a, 25), List(b, 50), List(i, 60))

You can use case (s: String) :: _ => s to sort by first element or case _ :: (i: Int) :: _ => i to sort by second element.

like image 45
senia Avatar answered Feb 16 '26 12:02

senia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!