← Scala EspañolChapter 06 of 13

Colecciones

## Objetivos de Aprendizaje - Dominar la jerarquia de colecciones de Scala - Trabajar con List, Set, Map, Array - Comprender colecciones inmutables vs mutables - Usar operaciones comunes de colecciones - Trabajar con Option ## Jerarquia de Colecciones ```text Traversable ├── Iterable │ ├── Seq │ │ ├── List, Vector, Array, ArrayBuffer │ │ ├── Range │ │ └── Queue, Stack │ ├── Set │ │ ├── HashSet, LinkedHashSet, TreeSet │ │ └── BitSet │ └── Map │ ├── HashMap, LinkedHashMap, TreeMap │ └── ListMap ``` ## List ### Creando Listas ```scala val fruits = List("apple", "banana", "cherry") val numbers = List(1, 2, 3, 4, 5) val empty = List() // Operador Cons val head :: rest = numbers // head: 1, rest: List(2, 3, 4, 5) // Construyendo con :: val newList = 0 :: numbers // List(0, 1, 2, 3, 4, 5) val combined = 1 :: 2 :: 3 :: Nil // List(1, 2, 3) ``` ### Operaciones de Lista ```scala val list = List(1, 2, 3, 4, 5) list.head // 1 list.tail // List(2, 3, 4, 5) list.last // 5 list.init // List(1, 2, 3, 4) list.length // 5 list.isEmpty // false // Concatenacion List(1, 2) ::: List(3, 4) // List(1, 2, 3, 4) List.concat(List(1, 2), List(3, 4)) // Igual // Reversa list.reverse // List(5, 4, 3, 2, 1) ``` ## Set ### Creando Sets ```scala val colors = Set("red", "green", "blue") val numbers = Set(1, 2, 3, 3, 3) // Duplicados eliminados: Set(1, 2, 3) val empty = Set() ``` ### Operaciones de Set ```scala val set = Set(1, 2, 3, 4, 5) set.contains(3) // true set(3) // true (igual que contains) set + 6 // Set(1, 2, 3, 4, 5, 6) set - 3 // Set(1, 2, 4, 5) set ++ Set(6, 7) // Set(1, 2, 3, 4, 5, 6, 7) set -- Set(3, 4) // Set(1, 2, 5) // Operaciones de conjuntos val set1 = Set(1, 2, 3) val set2 = Set(3, 4, 5) set1 union set2 // Set(1, 2, 3, 4, 5) set1 intersect set2 // Set(3) set1 diff set2 // Set(1, 2) ``` ## Map ### Creando Maps ```scala val ages = Map("Alice" -> 30, "Bob" -> 25) val kv = Map(("Alice", 30), ("Bob", 25)) val empty = Map[String, Int]() // Mapa mutable import scala.collection.mutable val mutableMap = mutable.Map("x" -> 1, "y" -> 2) ``` ### Operaciones de Map ```scala val map = Map("a" -> 1, "b" -> 2, "c" -> 3) map("a") // 1 (lanza excepcion si no se encuentra) map.get("a") // Some(1) map.getOrElse("d", 0) // 0 map.keys // Iterable(a, b, c) map.values // Iterable(1, 2, 3) map.contains("b") // true // Actualizacion (crea nuevo mapa para inmutable) val updated = map + ("d" -> 4) // Map(a -> 1, b -> 2, c -> 3, d -> 4) val removed = map - "b" // Map(a -> 1, c -> 3) ``` ## Array ### Creando Arrays ```scala val arr = Array(1, 2, 3, 4, 5) val arr2 = new Array[Int](5) // Array de 5 ceros val arr3 = Array.fill(3)("hello") // Array("hello", "hello", "hello") val arr4 = Array.range(1, 5) // Array(1, 2, 3, 4) ``` ### Operaciones de Array ```scala val arr = Array(1, 2, 3, 4, 5) arr(0) // 1 (actualizacion: arr(0) = 10) arr.length // 5 arr.toList // List(1, 2, 3, 4, 5) // Los arrays son mutables arr(0) = 10 arr.update(1, 20) ``` ## Inmutable vs Mutable ### Colecciones Inmutables (Por Defecto) ```scala import scala.collection.immutable._ val list = List(1, 2, 3) val newList = list :+ 4 // List(1, 2, 3, 4) - original sin cambios val map = Map("a" -> 1) val newMap = map + ("b" -> 2) // Map("a" -> 1, "b" -> 2) ``` ### Colecciones Mutables ```scala import scala.collection.mutable._ val buffer = ListBuffer[Int]() buffer += 1 buffer += 2 buffer ++= List(3, 4, 5) buffer.remove(0) buffer.toList // List(2, 3, 4, 5) val mutableMap = mutable.Map[String, Int]() mutableMap("a") = 1 mutableMap.put("b", 2) mutableMap.remove("a") ``` ## Operaciones Comunes ### map ```scala List(1, 2, 3).map(x => x * 2) // List(2, 4, 6) List(1, 2, 3).map(_ * 2) // List(2, 4, 6) Set(1, 2, 3).map(x => x * 2) // Set(2, 4, 6) ``` ### filter ```scala List(1, 2, 3, 4, 5).filter(x => x > 2) // List(3, 4, 5) List(1, 2, 3, 4, 5).filter(_ > 2) // List(3, 4, 5) ``` ### flatMap ```scala List(List(1, 2), List(3, 4)).flatMap(x => x) // List(1, 2, 3, 4) def getWords(line: String): List[String] = line.split(" ").toList List("Hello world", "Scala is fun").flatMap(getWords) // List(Hello, world, Scala, is, fun) ``` ### reduce ```scala List(1, 2, 3, 4, 5).reduce((a, b) => a + b) // 15 List(1, 2, 3, 4, 5).reduce(_ + _) // 15 List(1, 2, 3, 4, 5).reduceLeft(_ + _) // 15 // Con valor inicial List(1, 2, 3).fold(10)(_ + _) // 16 ``` ### flatten ```scala List(List(1, 2), List(3, 4)).flatten // List(1, 2, 3, 4) ``` ### Collect ```scala List(1, 2, 3, 4, 5).collect { case x if x % 2 == 0 => x * 2 } // List(4, 8) ``` ### Group By ```scala List(1, 2, 3, 4, 5, 6).groupBy(x => x % 2) // Map(0 -> List(2, 4, 6), 1 -> List(1, 3, 5)) ``` ### Take, Drop, SplitAt ```scala val list = List(1, 2, 3, 4, 5) list.take(3) // List(1, 2, 3) list.drop(3) // List(4, 5) list.splitAt(3) // (List(1, 2, 3), List(4, 5)) list.takeWhile(_ <= 3) // List(1, 2, 3) list.dropWhile(_ <= 3) // List(4, 5) ``` ### Sort ```scala List(3, 1, 4, 1, 5, 9).sorted // List(1, 1, 3, 4, 5, 9) List(3, 1, 4, 1, 5, 9).sortWith(_ < _) // List(1, 1, 3, 4, 5, 9) case class Person(name: String, age: Int) val people = List(Person("Bob", 30), Person("Alice", 25)) people.sortBy(_.name) // Ordenar por nombre people.sortBy(_.age) // Ordenar por edad ``` ## Range ```scala val r = 1 to 10 // Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val r2 = 1 until 10 // Range(1, 2, 3, 4, 5, 6, 7, 8, 9) val r3 = 1 to 10 by 2 // Range(1, 3, 5, 7, 9) val r4 = 10 to 1 by -2 // Range(10, 8, 6, 4, 2) ``` ## Option Option representa valores opcionales: ```scala val someValue: Option[Int] = Some(5) val noValue: Option[Int] = None // Emparejamiento de patrones someValue match { case Some(x) => println(s"Got value: $x") case None => println("No value") } // Obtencion segura val map = Map("a" -> 1) map.get("a") // Some(1) map.get("b") // None map.getOrElse("c", 0) // 0 // Map en Option someValue.map(_ * 2) // Some(10) noValue.map(_ * 2) // None // FlatMap en Option someValue.flatMap(x => if (x > 0) Some(x * 2) else None) // Some(10) ``` ## Views y Colecciones Perezosas ```scala val nums = (1 to 1000000).view // Las operaciones son perezosas - sin colecciones intermedias val result = nums.map(_ * 2).filter(_ > 100).take(5).toList // Para colecciones muy grandes val largeView = (1 to BigInt(999999999)).view ``` ## Resumen - Scala tiene colecciones inmutables (por defecto) y mutables - List es una lista enlazada simple, eficiente al prepender - Set almacena elementos unicos - Map almacena pares clave-valor - Array es mutable con tamaño fijo - Operaciones comunes: map, filter, flatMap, reduce, fold - Option representa valores opcionales (Some o None) - Views proporcionan evaluacion perezosa para colecciones grandes - Prefiere colecciones inmutables para codigo mas seguro y predecible

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →