首页  

Scala 集合操作     所属分类 scala 浏览量 676
可变 和 不可变 集合
默认采用 不可变集合

scala.collection.mutable 
scala.collection.immutable

常用的集合  List Set Map

List(3,1,2).sorted

List(List(1,2,3),List(4,5,6)).flatten
List(1, 2, 3, 4, 5, 6)

List(List(1,2,3),List(4,5,List(6,7))).flatten
List[Any] = List(1, 2, 3, 4, 5, List(6, 7))



val list1 = List(1, 1, 2, 2, 3, 3)
List[Int] = List(1, 1, 2, 2, 3, 3)
val set1 = Set(1, 1, 2, 2, 3, 3)
scala.collection.immutable.Set[Int] = Set(1, 2, 3)
val map1 = Map(1->1,2->2,3->3)
scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 2, 3 -> 3)
 
list1.map(_*2)
list1.filter(_ > 1)
list1.collect {case i if i > 1 => i * 2}

flatten 和 flatMap

flatMap 先 map 再 flatten

val list2 = List(List(1, 2,3), List(4, 5, 6))
list2.flatten
List[Int] = List(1, 2, 3, 4, 5, 6)

list2.flatMap(i => i.map(_ * 2))
List[Int] = List(2, 4, 6, 8, 10, 12)

case class Student(name: String,age: Int,sex: String)
val list3 = List(Student("cat",9,"m"), Student("dog",5,"m"), Student("tiger",20,"f"))
list3.map(_.name)
  List[String] = List(cat, dog, tiger)
  
list3.filter(_.sex == "m")
  List(Student(cat,9,m), Student(dog,5,m))

  
list3.collect{case s if s.sex == "m" => s}

ilter更加简洁

list3.filter(_.sex == "m").map(_.name)

list3.zipWithIndex
List[(Student, Int)] = List((Student(cat,9,m),0), (Student(dog,5,m),1), (Student(tiger,20,f),2))

将男学生和女学生分组,男学生组成一个集合,女学生组成一个集合

list3.groupBy(_.sex)scala.collection.immutable.Map[String,List[Student]] = Map(m -> List(Student(cat,9,m), Student(dog,5,m)), f -> List(Student(tiger,20,f)))

上一篇     下一篇
IDEA 远程调试

mac mvn 编译 找不到JDK

Scala map与flatMap

play scala hello world tutorial

Scala 下划线的用途

scala 匿名函数