Oktatás * Programozás 2 * Szkriptnyelvek * levelezősök Félévek Linkek * kalendárium |
Scala /
Array goodies
There are lots of useful methods for arrays and array buffers. For these methods, check out ArrayOps in the Scala Doc. Let's see some examples: scala> val a = Array(35, 47, 3, 24, 73, 6, 4) a: Array[Int] = Array(35, 47, 3, 24, 73, 6, 4) scala> a.count(_ > 20) // How many elems are > 20? res32: Int = 4 scala> a.filter(_ > 20) // Which elems are > 20? res33: Array[Int] = Array(35, 47, 24, 73) scala> a.partition(_ > 20) // take elems that satisfy the condition and take elems that don't res34: (Array[Int], Array[Int]) = (Array(35, 47, 24, 73),Array(3, 6, 4)) scala> a contains 24 res35: Boolean = true scala> val a = Array(1, 2, 2, 6, 2, 4, 1) a: Array[Int] = Array(1, 2, 2, 6, 2, 4, 1) scala> a.distinct // remove duplicates res36: Array[Int] = Array(1, 2, 6, 4) scala> a res37: Array[Int] = Array(1, 2, 2, 6, 2, 4, 1) scala> a.sum res38: Int = 18 scala> a.product res39: Int = 192 scala> a.max res40: Int = 6 scala> a.min res41: Int = 1 scala> a.reverse res42: Array[Int] = Array(1, 4, 2, 6, 2, 2, 1) Convert each elementscala> val a = Array("1", "2", "3") a: Array[String] = Array(1, 2, 3) scala> a.map(s => s.toInt) res10: Array[Int] = Array(1, 2, 3) // ----- it works with other collections too ----- scala> val b = ArrayBuffer("1", "2", "3") b: scala.collection.mutable.ArrayBuffer[String] = ArrayBuffer(1, 2, 3) scala> b.map(s => s.toInt) res9: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3) |
Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |