Learn Java for Web Development

(Tina Meador) #1

428 APPENDIX C: Introduction to Scala


Sets

A set is a collection that contains no duplicate elements. There are two kinds of sets, the immutable
and the mutable. Listing C-7 illustrates how to create an immutable set.


Listing C-7. Creating an Immutable Set


val set = Set(1, 2, 3, 2, 3)
println ("head -- "+set.head)
println("tail -- "+set.tail)
println("size -- "+set.size)
println("sum -- "+set.sum)


head -- 1


tail -- Set(2, 3)


size -- 3


sum -- 6


By default, Scala uses the immutable set. If you want to use the mutable set, you will have to import
scala.collection.mutable.Set. Listing C-8 illustrates how to create and use a mutable set.


Listing C-8. Creating a Mutable Set


import collection.mutable
val set = mutable.HashSet(1, 2, 3, 2, 3)
assert (set.size == 3)


Maps

A Scala map is a collection of key-value pairs. By default, Scala uses the immutable map. If you
want to use the mutable map, you’ll have to import the scala.collection.mutable.Map class
explicitly. Listing C-9 illustrates how to create and use an immutable map.


Listing C-9. Creating an Immutable Map


val map = Map("1" -> 1, "2" -> 2, "3" -> 3, "2" -> 2, "3" -> 3)


println ("head -- "+map.head)
println("tail -- "+map.tail)
println("size -- "+map.size)


head -- (1,1)


tail -- Map(2 -> 2, 3 -> 3)


size -- 3

Free download pdf