Free tutorials for Java, Eclipse and Web programming



Follow me on twitter

8. Collections

Scala provides collections, like List, Array and Map.

8.1. List

A List in Scala is immutatable, e.g. it is not possible to add and remove entries from a list. If you add or remove an element from a list you always create a modified copy of the original list.

				
package de.vogella.scala.collections;

  object Lists {
    def main(args: Array[String]) {
      val languages = List("Java", ".NET", "C++")
      println (languages)
      println (languages(2))
      println (languages.contains("Java"))
      // + should be replaced with ::: but the Eclipse does currenlty not support this
      val additionalLanguages = languages + ("COBOL") 
      println (additionalLanguages)
    }
   
  }
  
  


			

8.2. Array

Scala also supports Arrays. In an array you can change elements. It is not possible to add elements to an Array. This operation always created a modified copy of the existing array.

				
package de.vogella.scala.collections

object ArrayTest {
    def main(args: Array[String]) {
	val languages = Array("Java", ".NET")
	println (languages)
    }
}

			

8.3. Maps

The following shows how to create Maps.

				
package de.vogella.scala.collections

object MapTest {
    def main(args: Array[String]) {
	   val languages = Map("Scala"-> "JVM", "Java" -> "JVM", ".NET"-> "CLR");
	   println (languages("Scala"))
       
 }
}

			

8.4. Methods for Collections

The following demonstrates several methods for collections. The count, filter and exists method allow to define a closure which identifies the correct element(s).

				
package de.vogella.scala.collections

 object CollectionsMethods {
	def main(args: Array[String]) {
      val list= List(1, 2, 3, 4)
      // Prints number of all elements
       println (list.size )
      // Count only the elements which can be divided by 2
      println (list.count(i=> i %2==0))
      // Check if a elements in included in list
      println(list.exists(i=> i ==4));
      println(list.exists(i=> i ==5));
      // Using filter to get elements
      val newList = list.filter(i=> i>=3)
      println (newList)
      // Map does allow to transform a list
       val newList2 = list.map(i=> i*3)
       println (newList2)
    }
}