is there a way in Scala to sort an array of tuples using and arbitrary comparison function? In particular I need to sort and array of tuples by their second element, but I wante
If it's an Array
, it's probably typical to use in-place sorting algorithms. However, in idiomatic Scala code, mutable collections are usually not encouraged/used. If that's the case and you have am immutable collection (or would like to not modify the Array
in place), use sortWith
:
scala> val a = Array(1, 3, 2, 5)
a: Array[Int] = Array(1, 3, 2, 5)
scala> a.sortWith(_ > _)
res6: Array[Int] = Array(5, 3, 2, 1)
scala> a
res7: Array[Int] = Array(1, 3, 2, 5)
sorting an Array
or any other collection of tuples:
scala> val a = Array(('a', 1), ('b', 4), ('c', 5), ('d', 2))
a: Array[(Char, Int)] = Array((a,1), (b,4), (c,5), (d,2))
scala> a.sortWith(_._2 > _._2)
res4: Array[(Char, Int)] = Array((c,5), (b,4), (d,2), (a,1))
scala> a
res5: Array[(Char, Int)] = Array((a,1), (b,4), (c,5), (d,2))