|
| 1 | +object MapFunction extends App |
| 2 | +{ |
| 3 | + //Applying map function on a list |
| 4 | + val a = List(1,2,3,4,5,6) |
| 5 | + val f = (x:Int)=> x+1 |
| 6 | + |
| 7 | + println("a.map(f) :" + a.map(f)) |
| 8 | + println("a.map((x:Int) => x+1) : " + a.map((x:Int) => x+1)) |
| 9 | + println("a.map(x => x+1):" + a.map(x => x+1)) |
| 10 | + println("a.map(_ + 1):" + a.map(_ + 1)) |
| 11 | + println("a.map(1 + _):" + a.map(1 + _)) |
| 12 | + |
| 13 | + //This import is required to remove compilation warning as- |
| 14 | + //warning: there was one feature warning; re-run with -feature for details |
| 15 | + import scala.language.postfixOps |
| 16 | + println("a.map(1+):" + a.map(1+)) //since we have removed _ for 1+ above warning is displayed |
| 17 | + |
| 18 | + //Applying map function on a Set |
| 19 | + var b = Set("Brown", "Red", "Green", "Purple", "Grey", "Yellow") |
| 20 | + println("b.map(x => x.size):" + b.map(x => x.size)) //Remember, Set contains unique values only. |
| 21 | + println("b.map(_.size):" + b.map(_.size)) |
| 22 | + println("b.map(x => (x, x.size)): " + b.map(x => (x, x.size))) |
| 23 | + |
| 24 | + //Applying map function on a Map |
| 25 | + val fifaTeams = Map('Germany -> 4, 'Brazil -> 5 , 'Italy -> 4, 'Argentina -> 2 ) |
| 26 | + println("fifaTeams.map(t => (Symbol.apply(\"Team \" + t._1.name), t._2)) : " + fifaTeams.map(t => (Symbol.apply("Team " + t._1.name), t._2))) |
| 27 | + |
| 28 | + //Applying map function on a String |
| 29 | + println("\"Hello!\".map(x => (x+1)).toChar:" + "Hello!".map(x => (x+1).toChar)) |
| 30 | + |
| 31 | + //Applying map function on Some |
| 32 | + println("Some(4).map(1+) :" + Some(4).map(1+)) |
| 33 | + |
| 34 | + //Applying map function on None |
| 35 | + println("None.asInstanceOf[Option[Int]].map(1+) :" + None.asInstanceOf[Option[Int]].map(1+)) |
| 36 | +} |
| 37 | + |
| 38 | +/** |
| 39 | + Sample Output |
| 40 | +a.map(f) :List(2, 3, 4, 5, 6, 7) |
| 41 | +a.map((x:Int) => x+1) : List(2, 3, 4, 5, 6, 7) |
| 42 | +a.map(x => x+1):List(2, 3, 4, 5, 6, 7) |
| 43 | +a.map(_ + 1):List(2, 3, 4, 5, 6, 7) |
| 44 | +a.map(1 + _):List(2, 3, 4, 5, 6, 7) |
| 45 | +a.map(1+):List(2, 3, 4, 5, 6, 7) |
| 46 | +b.map(x => x.size):Set(6, 3, 5, 4) |
| 47 | +b.map(_.size):Set(6, 3, 5, 4) |
| 48 | +b.map(x => (x, x.size)): Set((Green,5), (Brown,5), (Red,3), (Yellow,6), (Grey,4), (Purple,6)) |
| 49 | +fifaTeams.map(t => (Symbol.apply("Team " + t._1.name), t._2)) : Map('Team Germany -> 4, 'Team Brazil -> 5, 'Team Italy -> 4, 'Team Argentina -> 2) |
| 50 | +"Hello!".map(x => (x+1)).toChar:Ifmmp" |
| 51 | +Some(4).map(1+) :Some(5) |
| 52 | +None.asInstanceOf[Option[Int]].map(1+) :None |
| 53 | +
|
| 54 | +**/ |
0 commit comments