In Scala, how to use Ordering[T] with List.min or List.max and keep code readable

前端 未结 6 578
轮回少年
轮回少年 2020-12-23 20:58

In Scala 2.8, I had a need to call List.min and provide my own compare function to get the value based on the second element of a Tuple2. I had to write this kind of code:

6条回答
  •  庸人自扰
    2020-12-23 21:40

    One thing you can do is use the more concise standard tuple type syntax instead of using Tuple2:

    val min = list.min(new Ordering[(String, Int)] { 
      def compare(x: (String, Int), y: (String, Int)): Int = x._2 compare y._2 
    })
    

    Or use reduceLeft to have a more concise solution altogether:

    val min = list.reduceLeft((a, b) => (if (a._2 < b._2) a else b))
    

    Or you could sort the list by your criterion and get the first element (or last for the max):

    val min = list.sort( (a, b) => a._2 < b._2 ).first
    

    Which can be further shortened using the placeholder syntax:

    val min = list.sort( _._2 < _._2 ).first
    

    Which, as you wrote yourself, can be shortened to:

    val min = list.sortBy( _._2 ).first
    

    But as you suggested sortBy yourself, I'm not sure if you are looking for something different here.

提交回复
热议问题