How to sort a list in Scala by two fields?

前端 未结 4 1323
执念已碎
执念已碎 2020-12-02 07:09

how to sort a list in Scala by two fields, in this example I will sort by lastName and firstName?

case class Row(var firstName: String, var lastName: String,         


        
4条回答
  •  清歌不尽
    2020-12-02 07:57

    Perhaps this works only for a List of Tuples, but

    scala> var zz = List((1, 0.1), (2, 0.5), (3, 0.6), (4, 0.3), (5, 0.1))
    zz: List[(Int, Double)] = List((1,0.1), (2,0.5), (3,0.6), (4,0.3), (5,0.1))
    
    scala> zz.sortBy( x => (-x._2, x._1))
    res54: List[(Int, Double)] = List((3,0.6), (2,0.5), (4,0.3), (1,0.1), (5,0.1))
    

    appears to work and be a simple way to express it.

提交回复
热议问题