Last active
August 29, 2015 14:16
-
-
Save betandr/74b100482eabb79134ab to your computer and use it in GitHub Desktop.
Scala: Lists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Lists { | |
val emptyList = List() | |
val otherEmptyList = Nil | |
val items = List("foo", "bar", "baz") | |
val consStyleItems = "foo" :: "bar" :: "baz" :: Nil // cons prepend to front of Nil list | |
val concatStyleItems = List("foo", "bar") ::: List("baz") | |
items(2) // returns 'baz' | |
items.count(s => s.length == 3) // counts number of items with length of three chars | |
items.drop(2) // drops first two elements and returns rest of list | |
items.dropRight(2) // drops RIGHT MOST two elements and returns rest of list | |
items.exists(s => s == "bar") // boolean: contains item? | |
items.forall(s => s.startsWith("b")) // Boolean: all items start with "b" | |
items.forall(s => s.length == 3) // Boolean: all items three chars long | |
items.foreach(print) | |
items.isEmpty // Boolean | |
items.head // first item | |
items.init // all but the last item | |
items.last // the last item | |
items.tail // list minus first element | |
items.length // Int | |
val extraItems = items ::: List("password", "extra") | |
extraItems.filter(s => s.length == 3) // filters only strings with three chars | |
extraItems.foreach(s => s.startsWith("b")) | |
extraItems.map(s => "x" + s + "x") | |
extraItems.map(s => if (s == "password") { "[redacted]" } else { s }) | |
extraItems.filterNot(s => s.length > 3) // new list without the matching items | |
extraItems.mkString(", ") // make a String out of the List | |
extraItems.reverse | |
extraItems.sortBy(s => s) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment