Created
October 28, 2020 16:52
-
-
Save rupeshtr78/266d94e1226c02f37a77c1bddc238f09 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 PlayGround | |
object ScalaCollectionsFoldReduceFlat { | |
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 | |
//foldreduce | |
firstTen.find(_ > 4) // Some(5) | |
firstTen.fold(0)(_ + _) // 55 // replace with sum | |
firstTen.foldLeft(0)(_ - _) // 55 | |
firstTen.foldRight(0)(_ - _) // -5 | |
evens.forall(_ >= 2) // true | |
firstTen.reduce(_ + _) // 55 replace with sum | |
firstTen.reduceLeft(_ - _) // -53 | |
firstTen.reduceRight(_ - _) // Int = -5 | |
//flatten | |
foo * 3 // foofoofoo | |
a.diff("foo") // " bar baz" | |
names.flatten // List(A, l, C, h, r, i, s, t, i, n, a, K, i, m) | |
names.flatMap(_.toUpperCase) // List(A, L, C, H, R, I, S, T, I, N, A, K, I, M) | |
a.foreach(println(_)) // prints one character per line | |
a.foreach(println) // prints one character per line | |
a.getBytes.foreach(println) // prints the byte value of each character, one value per line | |
firstTen.intersect(fiveToFifteen) // List(5, 6, 7, 8, 9, 10) | |
a.mkString(",") // f,o,o, ,b,a,r, ,b,a,z | |
a.mkString("->", ",", "<-") // ->f,o,o, ,b,a,r, ,b,a,z<- | |
a.par // a parallel array, ParArray(f, o, o, , b, a, r, , b, a, z) | |
a.replace('o', 'x') // fxx bar baz | |
a.replace("o", "x") // fxx bar baz | |
a.replaceAll("o", "x") // fxx bar baz | |
a.replaceFirst("o", "x") // fxo bar baz | |
firstTen.reverse // List(10, 9, 8, 7, 6, 5, 4, 3, 2, 1) | |
a.sortWith(_ < _) // " aabbfoorz" | |
a.sortWith(_ > _) // "zroofbbaa " | |
a.sorted // " aabbfoorz" | |
evens.union(odds) // List(2, 4, 6, 1, 3, 5) | |
Seq(1,2,3).updated(0,10) // List(10, 2, 3) | |
firstTen.view // scala.collection.SeqView[Int,List[Int]] = SeqView(...) | |
firstTen.withFilter(_ > 5) // scala.collection.generic.FilterMonadic[Int,List[Int]] | |
firstTen.withFilter(_ > 5).map(_ * 1) // List[Int] = List(6, 7, 8, 9, 10) | |
a.zip(0 to 10) // Vector((f,10), (o,11), (o,12), ( ,13), (b,14), (a,15), (r,16), ( ,17), (b,18), (a,19), (z,20)) | |
Seq(1,2,3).zipAll(Seq('a', 'b'), 0, 'z') // List((1,a), (2,b), (3,z)) | |
Seq(1,2).zipAll(Seq('a', 'b', 'c'), 0, 'z') // List((1,a), (2,b), (0,c)) | |
a.zipWithIndex // Vector((f,0), (o,1), (o,2), ( ,3), (b,4), (a,5), (r,6), ( ,7), (b,8), (a,9), (z,10)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment