Created
January 25, 2016 03:00
-
-
Save hossshy/89f63420ebf30b8b22f2 to your computer and use it in GitHub Desktop.
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
package chapter6 | |
/** | |
* Created by hoshi on 1/25/16. | |
*/ | |
object RangeMain { | |
def main(args: Array[String]) { | |
// Range | |
println(1 to 10) | |
println(1 until 10) | |
println(1 to 10 by 2) | |
println('a' to 'c') | |
val x = (1 to 10).toList | |
println(x) | |
// Stream | |
val stream = 1 #:: 2 #:: 3 #:: Stream.empty | |
println(stream) | |
val stream2 = (1 to Integer.MAX_VALUE - 1).toStream | |
println(stream2) | |
println(stream2.head) | |
println(stream2.tail) | |
// Tuples | |
//def sumSq(in: List[Double]): (Int, Double, Double) = in.foldLeft((0, 0d, 0d))((t, v) => (t._1 + 1, t._2 + v, t._3 + v * v)) | |
// more readable | |
def sumSq(in: List[Double]) : (Int, Double, Double) = in.foldLeft((0, 0d, 0d)) { | |
case ((cnt, sum, sq), v) => (cnt + 1, sum + v, sq + v * v) | |
} | |
println(sumSq(List(1,2,3,4,5))) | |
println(Tuple2(1,2)) | |
println((1,2)) | |
println(1 -> 2) | |
// Map | |
var p = Map(1 -> "David", 9 -> "Elwood") | |
println(p) | |
p += 8 -> "Archer" | |
println(p) | |
println(p(9)) | |
// println(p(88)) // NoSuchElementException | |
println(p.get(88)) | |
println(p.get(9)) | |
println(p.getOrElse(88, "Nobody")) | |
println(1 to 9 flatMap(p.get)) //Vector(David, Archer, Elwood) | |
println(1 to 9 map(p.get)) //Vector(Some(David), None, None, None, None, None, None, Some(Archer), Some(Elwood)) | |
p -= 9 | |
println(p) | |
println(p.values.exists(_.contains("z"))) | |
p ++= List(5 -> "Cat", 6 -> "Dog") | |
println(p) | |
p --= List(8, 6) | |
println(p) | |
def removeInvalid(in: Map[Int, Person]) = in.filter(kv => kv._2.valid) | |
// Mutable Collections | |
val immutableMap = Map(1 -> "a", 2 -> "b", 3 -> "c") | |
val newMap = immutableMap - 1 + (4 -> "d") | |
println(newMap) | |
println(immutableMap) | |
// immutable to mutable | |
val mutable = immutableMap.toBuffer | |
mutable += (5 -> "e") | |
println(mutable) | |
// mutable to immutable | |
val newMap2 = mutable.toMap | |
println(newMap2) | |
// mutable.Queue | |
var ints = scala.collection.mutable.Queue[Int]() | |
ints += 1 | |
ints += (2, 3) | |
ints.enqueue(4) | |
println(ints) | |
ints.dequeue() //FIFO | |
println(ints) | |
// mutable.Stack | |
val stack = scala.collection.mutable.Stack(1, 2, 3) | |
stack.push(4) | |
stack.push(5, 6, 7) | |
println(stack) | |
println(stack.pop) // LIFO | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment