Skip to content

Instantly share code, notes, and snippets.

@spoertsch
Last active December 25, 2015 01:59
Show Gist options
  • Save spoertsch/6899094 to your computer and use it in GitHub Desktop.
Save spoertsch/6899094 to your computer and use it in GitHub Desktop.
IPSWAYS Scala Meetup - Collections
// List (immutable)
val numbers: List[Int] = List(1, 2, 6, 34, 17, 42, 54, 100, 117, 1337)
// Map (immutable)
val map = Map("Test" -> 4, "ABC" -> 4)
// List API
// Filter
numbers.filter(x => x < 4)
numbers.filter(_ < 4)
// Map
numbers.map(x => x * x)
// foreach, Seiteneffekt (Unit)
numbers.foreach(x => println(x * x))
numbers.exists(_ == 42)
numbers.exists(_ == 0)
numbers.partition(_ > 100)
numbers.take(2)
numbers.takeWhile(_ < 100)
numbers.count(_ < 100)
numbers.mkString(", ")
numbers.reverse
val consList = "Test" :: "ABC" :: Nil
// Zip
val chars = List("a", "b", "c")
numbers.zip(chars)
// Fold -> Addieren einzelner Ergebnisse
case class Score(p1: Int, p2: Int)
val scores = Seq(Score(5, 1), Score(2, 5), Score(1, 5))
// The java way
var totalScoreP1: Int = 0
var totalScoreP2: Int = 0
for (score <- scores) {
totalScoreP1 += score.p1
totalScoreP2 += score.p2
}
s"Total score: ${totalScoreP1} : ${totalScoreP2}"
// List[Score] => (p1ScoreTotal: Int, p2ScoreTotal: Int)
val initialTotal = (0, 0)
// 1. (0, 0), Score(5, 1) => (5, 1)
// 2. (5, 1), Score(2, 5) => (5 + 2, 1 + 5)
// 3. (7, 6), Score(1, 5) => (7 + 1, 6 + 5)
// Result: (8, 11)
val totalScores = scores.foldLeft(initialTotal) ((total, current) => (total._1 + current.p1, total._2 + current.p2))
s"Total score: ${totalScores._1} : ${totalScores._2}"
// Parallel collections
numbers.par.filter(_ > 100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment