1、Scala中List、Map、Set等各类型函数操作汇总
package com.scala.study import scala.collection.immutable.{Queue, TreeMap}import scala.collection.mutable /** * Created by HP-PC on 2016/5/26. */ object ScalaCaseDemo { def main(args: Array[String]): Unit = { println(1 :: 2 :: List(3, 4)) //单个元素联合List:List(1, 2, 3, 4) //两个List进行联合成一个List:List(1, 2, 3, 4) println(List(1, 2) ::: List(3, 4)) println(List("Spark", "Hadoop", "Hive").head) //Spark println(List("Spark", "Hadoop", "Hive").tail) //List(Hadoop, Hive) //将List集合拆分成2个List集合:(List(1,2,3),List(4,5,6)) println(List(1, 2, 3, 4, 5, 6).span(_ < 4)) //将List集合中的元素用“—”进行拼接 println(List("a", "b", "c", "d").mkString("_")) //将List集合元素进行拆分,合并成一个大的List集合 println(List("Spark", "Hadoop").flatMap(_.toList)) //exists判断List集合中是否存在元素,forall是判断整行情况 println(List(List(1, 0, 0), List(0, 1, 0), List(0, 0, 0)).exists(row => row.forall(_ == 0))) /** * foldLeft就是每次计算的结果加上List集合中的元素 * 如:1+0=1,2+1=3,3+3=6,4+6=10,5+10=15,...=5050 */ println((1 to 100).toList.foldLeft(0)(_ + _)) /** * foldRight就是每次List集合中的元素减去计算结果 * 如:1-100 = -99,2-(-99) = 101,3-101 = -98,4-(-98) = 102,5-102 = -97 */ println(List(1, 2, 3, 4, 5).foldRight(100)(_ - _)) println(List.apply(1, 2, 3, 4, 5)) println(List("b", "e", "a", "f").sortWith(_ < _)) //List排序输出 println(List.make(3, 5)) //构造List重复元素:List(5,5,5) println(List.range(1, 5)) //List(1,2,3,4) println(List.range(1, 9, 3)) //List中的元素是按间隔生成:List(1,4,7) //拉链操作:List((a,1), (b,2), (c,3), (d,4), (e,5)) val zipped = "abcde".toList zip List(1, 2, 3, 4, 5) println(zipped) println(zipped.unzip) //解拉链:(List(a, b, c, d, e),List(1, 2, 3, 4, 5)) //List集合进行合并:List(1, 2, 3, 4, 5) println(List(List(1, 2), List(3, 4), List(5)).flatten) //List集合进行合并:List(1, 2, 3, 4, 5) println(List.concat(List(1, 2), List(3, 4), List(5))) //两个List按给定的函数进行操作:List(300, 1200) println(List.map2(List(100, 200), (List(3, 6)))(_ * _)) val empty = Queue[Int]() val queue1 = empty.enqueue(1) val queue2 = queue1.enqueue(List(2, 3, 4, 5)) println(queue2) val (element, left) = queue2.dequeue println(element + ":" + left) //创建可变Set val data = mutable.Set.empty[Int] data ++= List(2, 3, 4) data += 4 //Set:重复数据不会添加 println(data) data --= List(2, 3) //移除List集合 println(data) data.clear() //清空Set集合 println(data) //创建可变Map val map = mutable.Map.empty[String, String] map("Java") = "Hadoop" map += { "Scala" -> "Spark" } map += ("Scala" -> "Tachyon") //相同Key,value值覆盖 println(map) println(map("Java")) for ((k, v) <- map) println(k + ":" + v) //创建treeSet,输出是按升序排序的 val treeSet = mutable.TreeSet(9, 2, 3, 8, 6, 7, 5, 1) treeSet += 4 println(treeSet) val treeSetForStr = mutable.TreeSet("Spark", "Hadoop", "Kafka", "Tachyon") println(treeSetForStr) //创建treeMap val treemap = TreeMap("Scala" -> "Spark", "Java" -> "Hadoop") println(treemap) }}
时间: 2024-10-07 08:01:37