Title: Sorting Sequences
Slug: sorting_sequences
Summary: Sorting Sequences Using Scala.
Date: 2017-01-03 12:00
Category: Scala
Tags: Basics
Authors: Chris Albon

If you want to learn more, check out Scala Cookbook and Programming in Scala.

Create Two Vectors


In [4]:
// Create two vectors
val ages = Vector(23,42,12,34)
val lastName = Vector("Jackson", "Dillan", "Bower", "Stein")

Sort Alphabetically


In [5]:
// View the sequence alphabetically
lastName.sorted


Out[5]:
Vector(Bower, Dillan, Jackson, Stein)

Sort Ascending


In [6]:
// View the sequence in ascending order
ages.sorted


Out[6]:
Vector(12, 23, 34, 42)

Sort Descending


In [7]:
// View the sequence sorted using i > j
ages.sortWith(_ > _)


Out[7]:
Vector(42, 34, 23, 12)

Sort By Length


In [8]:
// Voew the sequence sorted by descending length
lastName.sortWith(_.length > _.length)


Out[8]:
Vector(Jackson, Dillan, Bower, Stein)