valnumbers= Seq(1,2,3,4,5,6)
//List(2, 4, 6, 8, 10, 12)
numbers.map(n=> n * 2)
valchars= Seq('a','b','c','d')
//输出为List(A, B, C, D)
chars.map(ch=> ch.toUpper)
val
abcd
=
Seq(
'a'
,
'b'
,
'c'
,
'd'
)
val
efgj
=
Seq(
'e'
,
'f'
,
'g'
,
'h'
)
val
ijkl
=
Seq(
'i'
,
'j'
,
'k'
,
'l'
)
val
mnop
=
Seq(
'm'
,
'n'
,
'o'
,
'p'
)
val
qrst
=
Seq(
'q'
,
'r'
,
's'
,
't'
)
val
uvwx
=
Seq(
'u'
,
'v'
,
'w'
,
'x'
)
val
yz
=
Seq(
'y'
,
'z'
)
val
alphabet
=
Seq(abcd, efgj, ijkl, mnop, qrst, uvwx, yz)
// List(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z)
alphabet.flatten
|
valabcd= Seq('a','b','c','d')
//List(A, a, B, b, C, c, D, d)
abcd.flatMap(ch=> List(ch.toUpper, ch))
scala> List(List(1,2),List(3,4)).flatMap(x=>x.map(x=>x*2))
res5: List[Int] = List(2, 4, 6, 8)
valnumbers=Seq(3,7,2,9,6,5,1,4,2)
//ture
numbers.forall(n=> n < 10)
//false
numbers.forall(n=> n > 5) 而 forall 函数就是为处理这类需求而创建的。
val
numbers
=
Seq(
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
,
10
)
numbers.filter(n
=
> n
%
2
==
0
) //seq(2,4,6,8,10)
|
case
class
Book(title
:
String, pages
:
Int)
val
books
=
Seq(
Book(
"Future of Scala developers"
,
85
),
Book(
"Parallel algorithms"
,
240
),
Book(
"Object Oriented Programming"
,
130
),
Book(
"Mobile Development"
,
495
)
)
books.filter(book
=
> book.pages >
=
120
)
|
val
numbers
=
Seq(
3
,
7
,
2
,
9
,
6
,
5
,
1
,
4
,
2
)
//(List(2, 6, 4, 2), List(3, 7, 9, 5, 1))
numbers.
partition
(n
=
> n
%
2
==
0
)
//
(List(Book(Parallel algorithms,240), Book(Object Oriented Programming,130)),
List(Book(Future of Scala developers,85), Book(Mobile Development,495)))
case
class
Book(title
:
String, pages
:
Int)
val
books
=
Seq(
Book(
"Future of Scala developers"
,
85
),
Book(
"Parallel algorithms"
,
240
),
Book(
"Object Oriented Programming"
,
130
),
Book(
"Mobile Development"
,
495
)
)
val
boo= books.partition(book =>book.pages %
2
==
0
)
println
(boo)
|
valnumbers=Seq(1,2,3,4,5)
//15
numbers.foldLeft(0)((res, n) => res + n)
在第一对括号中,我们放一个起始值。 在第二对括号中,我们定义需要对数字序列的每个元素执行的操作。 第一步,n = 0,然后它根据序列元素变化。
另一个关于 foldLeft 的例子,计算字符数:
val words = Seq("apple", "dog", "table")
//13
words.foldLeft(0)((resultLength, word) => resultLength + word.length)
val words = Seq("apple", "dog", "table")
//13
words.foldLeft(0)((resultLength, word) => resultLength + word.length)
valnumbers=Seq(11,2,5,1,6,3,9)
numbers.max//11
numbers.min//1
但实际操作的数据更加复杂。下面我们介绍一个更高级的例子,其中包含一个书的序列(查看源代码案例)。
caseclassBook(title:String, pages:Int)
valbooks=Seq(
Book("Future of Scala developers",85),
Book("Parallel algorithms",240),
Book("Object Oriented Programming",130),
Book("Mobile Development",495)
)
//Book(Mobile Development,495)
books.maxBy(book=> book.pages)
//Book(Future of Scala developers,85)
books.minBy(book=> book.pages)
val
num
1
=
Seq(
1
,
2
,
3
,
4
,
5
,
6
)
val
num
2
=
Seq(
4
,
5
,
6
,
7
,
8
,
9
)
//List(1, 2, 3)
num
1
.diff(num
2
)
//List(4, 5, 6)
num
1
.intersect(num
2
)
//List(1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9)
num
1
.union(num
2
)
|