xodhx4
4/22/2018 - 5:09 AM

Scala map, reduce, filter examples

[Scala functional Example] Examples of scala code that doing map, reduce, and filter #example #scala

/*filter 
//Filter array by their index using collect
//EX) Get part of array that its index is even
*/

// arr is List[Int]
val evenArr = arr
	.zipWithIndex
	.collect {
            case (vali, ind) if (ind%2==1) => vali
    }
/*reduce
//Sum of List that is only odd
*/

def f(arr:List[Int]):Int = arr.filter((i: Int) => i%2==1).reduceLeft(_ + _)
//map
//Read string, split them, and make them Int
*/

val real = StdIn.readLine()
      val exp = StdIn.readLine()
      
      /* Input is 
      //9 6 2015
      //6 6 2015
      */
      
      val realArray = real.split(" ").map(x => x.toInt)
      val expArray = exp.split(" ").map(x => x.toInt)
      
      //return is Array(9, 6, 2015)