LoginSignup
1
0

More than 5 years have passed since last update.

Scalaでタプルのリストをソート

Posted at

タプルのリストをソートしたいなぁ。

> Seq((4,1),(3,2),(2,3),(1,4)).sorted
List((1,4), (2,3), (3,2), (4,1))

できた。順序を逆転したいなぁ。

> Seq((4,1),(3,2),(2,3),(1,4)).sortBy{ case (x,y) => (-x, -y) }
List((1,4), (2,3), (3,2), (4,1))

sortWith使う場合はscala.math.Ordering.Implicits._をインポートしておかないと比較ができない

> import scala.math.Ordering.Implicits._
> Seq((4,1),(3,2),(2,3),(1,4)).sortWith(_ < _)
List((1,4), (2,3), (3,2), (4,1))

真偽値がまざっててもソートできるぜい。

> Seq((true,1),(false,2),(true,3),(false,4)).sorted
List((false,2), (false,4), (true,1), (true,3))
> Seq((true,1),(false,2),(true,3),(false,4)).sortBy{ case (x,y) => (!x,-y) }
List((true,3), (true,1), (false,4), (false,2))

trueのほうが大きいことがわかる。

参考 http://stackoverflow.com/questions/11102393/how-to-lexicographically-compare-scala-tuples

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0