Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort the list without changing order in scala

Tags:

scala

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

I want output as a different list which is in sorted order based on the middle element of each tuple in the list and first & third tuple's order should not be changed. Its like swapping the second tuple only.

Expected answer is:

List((2,1,1), (3,4,4) , (5,5,3), (9,8,2))
like image 713
Mahek Shah Avatar asked Jan 08 '23 12:01

Mahek Shah


1 Answers

zip and unzip and their variants are your friends for this kind of thing.

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
}
like image 98
tryx Avatar answered Jan 15 '23 14:01

tryx