您的位置:首页 > 理论基础 > 数据结构算法

Scala2.11.7学习笔记(四)常用数据结构

2015-09-28 14:22 603 查看
鲁春利的工作笔记,[b][b]好记性不如烂笔头[/b][/b]

1、Array
http://www.scala-lang.org/api/current/#scala.Array
Arrays are mutable, indexed collections of values.
Array[T]
is Scala's representation for Java's
T[]
.
var array = new Array[数据类型](数组长度);
说明:数组成员初始化,Int类型默认会初始化为0,String类型会初始化为Null。
var array = Array[数据类型](数组元素值);
说明:数组声明时若给出初值,Scala能够进行类型推断,因此可以不用声明数组类型和长度。
package com.lucl.scala

import scala.collection.mutable.ArrayBuffer

/**
* @author luchunli
*/
object ArrayDataStructure {
def main(args: Array[String]): Unit = {
/**
* 定长数组
*/
// new时指定类型及长度,指定变量类型: Array[Int],可以省略
var array1 = new Array[Int](5);
{
for (i <- 0 until 5) array1(i) = i + 1;
}
// 5, 4, 3, 2, 1,
for (i <- array1.reverse) print(i + ", ");
println();

// 直接赋固定值,Scala能够进行类型推导
var array2 = Array(1, 2, 3, 4, 5);
// 1, 2, 3, 4, 5,
array2.foreach { x => print(x + ", ") }
println();
println(array2.max + "\t" + array2.min)  // 5 1

/**
* 变长数组,scala.collection.mutable包
*/
var arrBuffer = new ArrayBuffer[String](5);
println(arrBuffer.length)    // 0
arrBuffer ++= Array("hello");
println(arrBuffer.length)    // 1

/**
* 定长数组转变长数组
*/
println(array2.toBuffer);

/**
* 变长数组转定长数组
*/
println(arrBuffer.toArray);

/**
* zip操作
*/
var array3 = Array(1, 2, 3);
var array4 = Array("a", "b", "c");

var tuple = array3 zip array4;  // 得到tuple
// (1,a) (2,b) (3,c)
for (i <- tuple) print(i + " ");  //
println();

//
val array5 = Array("hello you", "hello me");
val retVal = array5.flatMap { x => x.split(" ") }
// hello you, hello me
println(array5.mkString(", "));
// hello, you, hello, me
println(retVal.mkString(", "));
}
}
多维数组

val matrix = Array.ofDim[Int](3, 4);        // 三行四列的二维数组
matrix(2)(1) = 42;

val triangle = new Array[Array[Int]](10);
for (i <- 0 until triangle.length) {
triangle(i) = new Array[Int](i + 1);
}


2、Lists
http://www.scala-lang.org/api/current/#scala.collection.immutable.List

Scala中提供了List类,和Java的List不同,Scala的List对象是不可修改的。
A class for immutable linked lists representing ordered collections
of elements of type.
构建列表的两个基础是:
scala.Nil表示空列表;
scala.::从已有的列表构建新列表。
::读作cons,cons操作符有两个参数:一个类型为T的元素和一个类型为List(T)的对象,它会把两个参数合到一起创建一个新的List(T)值。
val list = List(元素值列表);
说明:元素必须为同一类型。
package com.lucl.scala

import scala.collection.mutable.ListBuffer

/**
* @author luchunli
*/
object ListDataStructure {
def main(args: Array[String]): Unit = {
// : List[String] 是可以省略的
val list : List[String] = List("hello", "you", "hello", "me");
/**
* 代码块
*/
list.foreach
{ x =>
{
if (x.equals("hello"))
{
print(x + ", ");
}
}
}
println();
println("----------------------------");
println();

/**
* Nil空列表和::构建新的列表
*/
val list2 = 1 :: 2 :: 3 :: Nil;  // 只能用在尾部
val list3 = "hello you" :: "hello me" :: List();

val retVal = list3.flatMap
{ x =>
{
x.split(" ");
}
}
// List(hello, you, hello, me)
println(retVal);
val retMap = retVal.map { x => (x, 1) }

/**
hello : 1
you : 1
hello : 1
me : 1
*/
for ((k, v) <- retMap) println(k + " : " + v);

/**
* 可变List,ListBuffer
*/
var listBuf = ListBuffer(1, 2, 3, 4, 5);
}
}


3、Set
http://www.scala-lang.org/api/current/#scala.collection.mutable.Set

和java中Set类似,Key,分两个包定义:
可变: scala.collection.mutable
不可变: scala.collection.immutable
缺省情况Set为immutable Set 。
package com.lucl.scala

/**
* @author luchunli
*/
object SetDataStructure {
def main(args: Array[String]): Unit = {
// 说明:Set中数据是会去重的,也就是两个hello实际使用的时候只会有一个
val sset = Set("hello", "world", "hello", "me");
// hello, world, me,
sset.foreach { x => print(x + ", "); }
println();
sset.+("new");  // 不可对sset重新赋值,这里实际返回了一个新的set

// 不可变set
var iset = scala.collection.mutable.Set("hello", "world", "hello", "me");
iset += "new";    // 可调用+=
}
}


4、Map
scala.collection.Map
scala.collection.immutable.Map      # 可变映射
scala.collection.immutable.HashMap
scala.collection.mutable.Map        # 不可变映射
scala.collection.mutable.HashMap
说明:默认为不可变映射。

// 不可变映射
val map = Map(key1 -> value1, key2 -> value2, key3->value3);
//
val map = Map((key1, value1), (key2, value2), (key3, value3))
// 可变映射需指定全类名
val map = scala.collection.mutable.Map((key1, value1), (key2, value2), (key3, value3));
//
val map = new scala.collection.mutable.Map[T1, T2]()
获取对应键的值
val value = Z(key);        // 返回值
val value = Z.get(key);    // 返回对象
说明:
当映射中不包含对应的键时,会抛出异常。
利用contains方法检查映射中是否有某个键,val c = Z.contains(key); // 返回boolean值
或者通过组合调用val d = Z.getOrElse(key, 0); 存在则返回否则返回0

package com.lucl.scala

/**
* @author luchunli
*/
object MapDataStructure {
def main(args: Array[String]): Unit = {
/**
* 不可变 ,scala.collection.immutable.Map
*/
val map1 = Map( 1-> "I", 2 -> "II", 3 -> "III", 4 -> "IV");
for ((k, v) <- map1) println(k + " : " + v);  // 显示key和value
for ((k, _) <- map1) println(k);              // 只显示key
for ((_, v) <- map1) println(v);              // 只显示value

val map2 = Map[String, Int]();
map2 + (("zhangsan", 18), ("wangwu", 21));  // 可以添加元素,但是不能+=
map2 + ("lisi" -> 20, "zhaoliu" -> 19);

/**
* 可变
*/
val hm = scala.collection.mutable.HashMap(1 -> "hi", 2 -> "there");
hm += ((3, "three"), (4, "four"));    // 增加元素
hm -= 1;                              // 删除元素

map2.keys.foreach { x => println(x); }    // 获取key
map2.values.foreach { x => println(x); }  // 获取value

}
}


5、Tuples
Scala 中另外一个很有用的容器类为Tuples,和List不同的Tuples可以包含不同类型的数据,而List只能包含同类型的数据。
一旦定义了一个元组,可以使用._和索引来访问员组的元素(矢量的分量,注意和数组不同的是,元组的索引从1开始)。
scala> val paris=(123, "abc")
paris: (Int, String) = (123,abc)

scala> println (paris._1);
123

scala> println (paris._2);
abc

scala> var tuple = (1, 2.1, "spark");
tuple: (Int, Double, String) = (1,2.1,spark)

scala> val (first, second, third) = tuple;
first: Int = 1
second: Double = 2.1
third: String = spark

scala> val (fa, _, _) = tuple;
fa: Int = 1

scala> "Rocky Spark".partition(_.isUpper);
res0: (String, String) = (RS,ocky park)

scala>


6、zip方法
把几个集合结合起来
scala> val one = Array('a', 'b', 'c');
one: Array[Char] = Array(a, b, c)

scala> val two = Array(1, 2, 3);
two: Array[Int] = Array(1, 2, 3)

// 生成一个新的数组
scala> val three = one zip two;
three: Array[(Char, Int)] = Array((a,1), (b,2), (c,3))

scala> val three01 = two zip one;
three01: Array[(Int, Char)] = Array((1,a), (2,b), (3,c))

// 生成一个以数组one为键,数组two为值的映射
scala> val four = one zip two toMap;
warning: there were 1 feature warning(s); re-run with -feature for details
four: scala.collection.immutable.Map[Char,Int] = Map(a -> 1, b -> 2, c -> 3)

scala> four.toMap;
res58: scala.collection.immutable.Map[Char,Int] = Map(a -> 1, b -> 2, c -> 3)


本文出自 “闷葫芦的世界” 博客,请务必保留此出处http://luchunli.blog.51cto.com/2368057/1698784
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: