Skip to content

Instantly share code, notes, and snippets.

@rupeshtr78
Created October 28, 2020 16:48
Show Gist options
  • Save rupeshtr78/319e4c880f41dbb32dd869209ddedd12 to your computer and use it in GitHub Desktop.
Save rupeshtr78/319e4c880f41dbb32dd869209ddedd12 to your computer and use it in GitHub Desktop.
package PlayGround
object ScalaCollectionsSortGroup {
val evens = List(2,4,6)
val odds = List(1,3,5)
val a = "foo bar baz"
val foo = "foo"
val bar = "bar"
val names = List("Al","Chistina","Kim")
val firstTen = (1 to 10).toList
val fiveToFifteen = (5 to 15).toList
//Sorting
//a.sortBy // this is a bit long; see below
a.sortWith(_ < _) // " aabbfoorz"
a.sortWith(_ > _) // "zroofbbaa "
a.sorted // " aabbfoorz"
case class Person(firstName: String, lastName: String)
val fred = Person("Fred", "Flintstone")
val wilma = Person("Wilma", "Flintstone")
val barney = Person("Barney", "Rubble")
val betty = Person("Betty", "Rubble")
val people = List(betty, wilma, barney, fred)
people.sortBy(n => (n.lastName, n.firstName))
people.sortBy(n => (n.firstName))
//Grouping methods
firstTen.groupBy(_ > 5) // Map(false -> List(1, 2, 3, 4, 5), true -> List(6, 7, 8, 9, 10))
firstTen.grouped(2) // Iterator[List[Int]] = non-empty iterator
firstTen.grouped(2).toList // List(List(1, 2), List(3, 4), List(5, 6), List(7, 8), List(9, 10))
firstTen.grouped(5).toList // List(List(1, 2, 3, 4, 5), List(6, 7, 8, 9, 10))
a.partition(_ > 'e') // (foorz, " ba ba") // a Tuple2
firstTen.partition(_ > 5) // (List(6, 7, 8, 9, 10),List(1, 2, 3, 4, 5))
firstTen.sliding(2) // Iterator[List[Int]] = non-empty iterator
firstTen.sliding(2).toList // List(List(1, 2), List(2, 3), List(3, 4), List(4, 5), List(5, 6), List(6, 7), List(7, 8), List(8, 9), List(9, 10))
firstTen.sliding(4).toList // List(List(1, 2, 3, 4), List(2, 3, 4, 5), List(3, 4, 5, 6), List(4, 5, 6, 7), List(5, 6, 7, 8), List(6, 7, 8, 9), List(7, 8, 9, 10))
firstTen.sliding(2,2).toList // List(List(1, 2), List(3, 4), List(5, 6), List(7, 8), List(9, 10))
firstTen.sliding(2,3).toList // List(List(1, 2), List(4, 5), List(7, 8), List(10))
firstTen.sliding(2,4).toList // List(List(1, 2), List(5, 6), List(9, 10))
firstTen.span(_ < 5) // (List(1, 2, 3, 4),List(5, 6, 7, 8, 9, 10))
a.split(" ") // Array(foo, bar, baz)
a.splitAt(3) // (foo," bar baz")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment