Sort list without reordering in scala

val a = List((2,5,1),(3,8,4), (5,4,3) ,(9,1,2))

I want the output to be a different list, which is in sorted order based on the middle element of each tuple in the list, and the first and third order of the tuples should not change. This is like replacing a second tuple.

Expected Answer:

List((2,1,1), (3,4,4) , (5,5,3), (9,8,2))
+4
source share
2 answers

As shown below, you can sort the 2nd element separately and pin them together

a.zip(a.map(_._2).sorted).map{ case((a,b,c), sortedB) => (a,sortedB,c)}
// res = List((2,1,1), (3,4,4), (5,5,3), (9,8,2))
+3
source

zipand unzip, and their options are your friends for these kinds of things.

val x = List((2,5,1),(3,8,4), (5,4,3) ,(9,1,2))
val y = x.unzip3 match {
  case (a,b,c) => (a, b.sorted,c).zipped.toList
}
+6
source

Source: https://habr.com/ru/post/1608264/


All Articles